242. Valid Anagram - Explanation
Description
Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
Example 1:
Input: s = "racecar", t = "carrace"
Output: trueExample 2:
Input: s = "jar", t = "jam"
Output: falseConstraints:
1 <= s.length, t.length <= 5 * 10^4sandtconsist of lowercase English letters.
Topics
Recommended Time & Space Complexity
You should aim for a solution with O(n + m) time and O(1) space, where n is the length of the string s and m is the length of the string t.
Hint 1
A brute force solution would be to sort the given strings and check for their equality. This would be an O(nlogn + mlogm) solution. Though this solution is acceptable, can you think of a better way without sorting the given strings?
Hint 2
By the definition of the anagram, we can rearrange the characters. Does the order of characters matter in both the strings? Then what matters?
Hint 3
We can just consider maintaining the frequency of each character. We can do this by having two separate hash tables for the two strings. Then, we can check whether the frequency of each character in string s is equal to that in string t and vice versa.
Prerequisites
Before attempting this problem, you should be comfortable with:
- Hash Maps - Using dictionaries or hash tables to count character frequencies
- Sorting - Sorting strings or arrays to compare elements in a consistent order
- Arrays - Using fixed-size arrays as an efficient alternative to hash maps for limited character sets
1. Sorting
Intuition
If two strings are anagrams, they must contain exactly the same characters with the same frequencies.
By sorting both strings, all characters will be arranged in a consistent order.
If the two sorted strings are identical, then every character and its count match, which means the strings are anagrams.
Algorithm
- If the lengths of the two strings differ, return
falseimmediately because they cannot be anagrams. - Sort both strings.
- Compare the sorted versions of the strings:
- If they are equal, return
true. - Otherwise, return
false.
- If they are equal, return
Time & Space Complexity
- Time complexity:
- Space complexity: or depending on the sorting algorithm.
Where is the length of string and is the length of string .
2. Hash Map
Intuition
If two strings are anagrams, they must use the same characters with the same frequencies.
Instead of sorting, we can count how many times each character appears in both strings.
By using two hash maps (or dictionaries), we track the frequency of every character in each string.
If both frequency maps match exactly, then the strings contain the same characters with same frequencies, meaning they are anagrams.
Algorithm
- If the two strings have different lengths, return
falseimmediately. - Create two hash maps to store character frequencies for each string.
- Iterate through both strings at the same time:
- Increase the character count for
s[i]in the first map. - Increase the character count for
t[i]in the second map.
- Increase the character count for
- After building both maps, compare them:
- If the maps are equal, return
true. - Otherwise, return
false.
- If the maps are equal, return
Time & Space Complexity
- Time complexity:
- Space complexity: since we have at most different characters.
Where is the length of string and is the length of string .
3. Hash Table (Using Array)
Intuition
Since the problem guarantees lowercase English letters, we can use a fixed-size array of length 26 to count character frequencies instead of a hash map.
As we iterate through both strings simultaneously, we increment the count for each character in s and decrement the count for each character in t.
If the strings are anagrams, every increment will be matched by a corresponding decrement, and all values in the array will end at 0.
This approach is efficient because it avoids hashing and uses constant space.
Algorithm
- If the lengths of the strings differ, return
falseimmediately. - Create a frequency array
countof size26initialized to0. - Iterate through both strings:
- Increment the count at the index corresponding to
s[i]. - Decrement the count at the index corresponding to
t[i].
- Increment the count at the index corresponding to
- After processing both strings, scan through the
countarray:- If any value is not
0, returnfalsebecause the frequencies differ.
- If any value is not
- If all values are
0, returntruesince the strings are anagrams.
Time & Space Complexity
- Time complexity:
- Space complexity: since we have at most different characters.
Where is the length of string and is the length of string .
Common Pitfalls
Forgetting to Check Length First
If two strings have different lengths, they cannot be anagrams. Skipping this early check means wasting time processing strings that could never match. Always compare lengths first and return false immediately if they differ.
Case Sensitivity Issues
When the problem specifies lowercase letters only (as in this problem), case sensitivity is not an issue. However, if the problem allows mixed case, forgetting to normalize to the same case (e.g., converting both strings to lowercase) will cause incorrect results where "Listen" and "Silent" would wrongly be considered non-anagrams.
Sign in to join the discussion