Coding Challenge from Leetcode - Valid Anagram
Went live to do a coding challenge from Leetcode.com called “Valid Anagram”.
Problem: Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Solution summary: 1. either sort both strings and check if they are equal, or 2. use a letter frequency map to compare them
1. Sort both strings - O(n log n) time
2. Check if they are equal to know if an anagram
1. Loop through first string, putting each letter into the map, and incrementing the value (frequency) per letter
2. Loop through the second string, checking if the letter is in the map; if so decrement the value (frequency); if not, return false (not an anagram)
3. Loop through the map and if any value is not zero, return false (not an anagram)
4. If gotten to this point without returning false, then return true (is an anagram)
Let me know if you have any questions or see ways I could have optimized!
Problem: Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Solution summary: 1. either sort both strings and check if they are equal, or 2. use a letter frequency map to compare them
Option 1: Sorting strings
1. Sort both strings - O(n log n) time
2. Check if they are equal to know if an anagram
Option 2: Use frequency map
1. Loop through first string, putting each letter into the map, and incrementing the value (frequency) per letter
2. Loop through the second string, checking if the letter is in the map; if so decrement the value (frequency); if not, return false (not an anagram)
3. Loop through the map and if any value is not zero, return false (not an anagram)
4. If gotten to this point without returning false, then return true (is an anagram)
Let me know if you have any questions or see ways I could have optimized!