To determine whether s and t are anagrams, we compare their character multisets using a single frequency map:
- Early exit by length: If
s.length !== t.length, they cannot be anagrams β return false. - Build counts from
s: Create a hashmapcharCounts. For each characterchins, incrementcharCounts[ch]. - Consume with
t: Iterate characters oft:- If
chis not incharCounts, thentcontains more ofchthansβ not an anagram β return false. - Otherwise, decrement
charCounts[ch]. If it becomes zero, remove the entry.
- If
- Final check: After consuming all of
t, ifcharCountsis empty, thensandtcontain exactly the same multiset of characters β return true. Otherwise, return false.
Why this works:
By incrementing counts for every character in s and then decrementing for each character in t,
the algorithm checks whether the two strings perfectly balance each otherβs character frequencies.
If a deficit occurs during processing (a missing or overused character) or if any counts remain afterward (charCounts map is not empty),
the balance is broken β meaning the strings differ in frequency.
If processing completes with no deficits and the charCounts map is empty,
it confirms that s and t contain exactly the same multiset of characters,
proving they are true anagrams.