Anagram Detection
DSA · Arrays & Stringssyntax
Two strings are anagrams if they have identical character frequencies.
Approach 1: Sort both and compare.
Approach 2: Build frequency map and compare.example
// JavaScript
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const freq = {};
for (const ch of s) freq[ch] = (freq[ch] || 0) + 1;
for (const ch of t) {
if (!freq[ch]) return false;
freq[ch]--;
}
return true;
}
# Python
def is_anagram(s, t):
if len(s) != len(t):
return False
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
for ch in t:
if freq.get(ch, 0) == 0:
return False
freq[ch] -= 1
return Trueoutput
is_anagram('listen', 'silent') → TrueNote Frequency map: O(n) time, O(1) space (bounded by alphabet size). Sorting approach: O(n log n). Always ask: are inputs lowercase only? Unicode? This affects space analysis. Follow-up: find all anagram groups in a list of words.