Home
DSA Patterns
Hash Map
Valid Anagram
Valid Anagram
Decide whether two strings are anagrams by counting letters in a hash map.
Problem Understanding
Valid Anagram: given two strings s and t, return true if t is an anagram of s — the same letters, each used the same number of times, in any order.
Examples: s = "anagram", t = "nagaram" is true. s = "rat", t = "car" is false.
Attempt 1: Sort Both Strings
Sort the letters of both strings and compare: anagrams sort to the same string. It is correct and short, but sorting costs O(n log n) time. The question underneath — does every letter appear the same number of times in both? — can be answered by counting, without ordering anything.
The Intuition: Count, Then Spend
A hash map from letter to count turns the question into bookkeeping:
- If the lengths differ, return
falseimmediately. - Walk
sand add one to each letter's count. - Walk
tand spend one count per letter. If a letter's count is already0,thas more of that letter thans— returnfalse.
If t finishes without running out of anything, the strings are anagrams. The length check is what makes that last step safe: equal lengths and nothing overspent means every count ended at exactly 0.
Interactive Walkthrough
s = "anagram", t = "nagaram"
LENGTHS MATCH
s
0
1
2
3
4
5
6
t
0
1
2
3
4
5
6
Answer
—
count (letter:count)
Empty
Both strings have 7 letters. Start an empty count
Next
s[0] = 'a': count['a'] is now 1
s
t
Both strings are drawn as rows. The first pass walks s while the count map beside the figure grows; the second walks t while the counts fall and matched letters grey out. A letter of t that finds its count at 0 ends the run.
