05. Check if Two Strings are Anagrams
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
How It Works & Algorithmic Design
An anagram contains the exact same characters with the exact same frequencies, reordered.
- Length Pre-Check: If
s.length !== t.length, they cannot be anagrams. Returnfalseimmediately. - Frequency Map: Traverse string
sand record character counts in a Hash Map (or a fixed 26-element array for lowercase English letters). - Frequency Verification: Traverse string
t. For each character, check if it exists in the map with a count $> 0$. Decrement its count in the map. If a character is missing or its count reaches negative, returnfalse. - Completion: If all characters in
tmatch and exhaust the counts ins, returntrue.
Why This Approach Works Best
Sorting both strings takes $O(n \log n)$ time. Using a frequency map checks anagrams in $O(n)$ time complexity and $O(k)$ space (where $k$ is the alphabet size, $O(1)$ for fixed character sets).
Example Walkthrough 1
s = "listen", t = "silent"
Same letters, different order.
s map: {l:1, i:1, s:1, t:1, e:1, n:1} -> t matches every key count exactly.
Frequency counts balance out to zero.
true
Valid anagram pair.
Answer: Anagram verification using frequency map
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (const ch of s) count[ch] = (count[ch] || 0) + 1;
for (const ch of t) {
if (!count[ch]) return false;
count[ch]--;
}
return true;
}Count character occurrences in the first string and verify them against the second string.
Always check string lengths first for instant early termination.
Frequency map eliminates the need for $O(n \log n)$ sorting operations.
For lowercase ASCII strings, a fixed 26-element array can replace a dynamic hash table for better performance.