Coding Interview PatternsValid Anagram
EasyHash Maps
Valid Anagram
Explanation & Solution
Description
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, using all the original letters exactly once.
Input: s = "anagram", t = "nagaram"
Output: true
Explanation: Rearranging the letters of "nagaram" produces "anagram".
Constraints
1 <= s.length, t.length <= 5 * 10^4sandtconsist of lowercase English letters.
Approach
Hash Maps pattern
1. Quick Length Check
- If the two strings have different lengths, they cannot be anagrams — return
falseimmediately
2. Count Characters in s
- Create a
Mapto store the frequency of each character ins - Iterate through
s, incrementing the count for each character
3. Decrement Counts Using t
- Iterate through
t, and for each character: - If the character is not in the map or its count is 0, return
false—thas an extra character not ins - Otherwise, decrement the count by 1
4. Return True
- If we finish iterating through
twithout returningfalse, all characters match in frequency - Since both strings have the same length and all counts were properly decremented,
tis a valid anagram ofs
Key Insight
- Two strings are anagrams if and only if they have the same character frequencies
- Using a hash map to count characters in one string and decrement with the other avoids sorting
Time
O(n)two linear passes through the stringsSpace
O(1)the map holds at most 26 entries (lowercase English letters)Visualization
Input:
[a, n, a, g, r, a, m], t = nagaram
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps