Q10: Valid Anagram
Given two strings s and t, return true if t is an anagram of s (contains exact same character frequencies).
Frequency Map Anagram Check
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (let char of s) {
count[char] = (count[char] || 0) + 1;
}
for (let char of t) {
if (!count[char]) return false;
count[char]--;
}
return true;
}
console.log(isAnagram('anagram', 'nagaram')); // true💡 Increments character counts for string
s and decrements for string t. If a character in t has zero count or doesn't exist, strings are not anagrams.Key Takeaways
- Return false early if string lengths differ.
- Use a single frequency map or fixed 26-character array to count frequencies.
Knowledge Check
What is the space complexity if solving anagram verification using frequency map over ASCII/lowercase letters?