Check whether two strings contain the same letters with the same counts.
Start with the concrete trace below. It shows the state the algorithm must carry as it runs.
Problem trace
Valid Anagram: Two strings are anagrams exactly when their character-count maps are equal.
Input and goalCheck whether two strings contain the same letters with the same counts.
Initialize both countersCounter starts with no entries for either string; the divider separates first="aab" from second="aba".
count firsta0a1b2|3a4b5a6
examplefirst = "aab", second = "aba"mapLabelCounter(first) and Counter(second)
Counter(first) and Counter(second)empty
Count the first aReading first[0]="a" changes the left count for a from 0 to 1.
left a: 0 -> 1a0a1b2|3a4b5a6
examplefirst = "aab", second = "aba"
saved statealeft 1 | right 0
Count the repeated aReading first[1]="a" changes the same left entry from 1 to 2.
a0left a: 1 -> 2a1b2|3a4b5a6
examplefirst = "aab", second = "aba"
saved statealeft 2 | right 0
Finish the first counterReading first[2]="b" adds b:1, so Counter(first) is {a:2, b:1}.
a0a1left b: 0 -> 1b2|3a4b5a6
examplefirst = "aab", second = "aba"leftCounter{a:2, b:1}
saved statealeft 2 | right 0bleft 1 | right 0
Start the second counterCounter(second) is independent. Reading second[0]="a" sets its a count to 1.
a0a1b2|3right a: 0 -> 1a4b5a6
examplefirst = "aab", second = "aba"
saved statealeft 2 | right 1bleft 1 | right 0
Count b in the second stringReading second[1]="b" sets its b count to 1.
a0a1b2|3a4right b: 0 -> 1b5a6
examplefirst = "aab", second = "aba"
saved statealeft 2 | right 1bleft 1 | right 1
Finish the second counterReading second[2]="a" changes its a count from 1 to 2, producing {a:2, b:1}.
a0a1b2|3a4b5right a: 1 -> 2a6
examplefirst = "aab", second = "aba"rightCounter{a:2, b:1}
saved statealeft 2 | right 2bleft 1 | right 1
Compare the complete mapsBoth keys and counts agree: a has 2 on each side and b has 1 on each side, so Counter(first) == Counter(second).
a0a1left completeb2|3a4b5right completea6
examplefirst = "aab", second = "aba"comparison{a:2,b:1} = {a:2,b:1}resulttrue
saved statealeft 2 = right 2bleft 1 = right 1
Recognize it
Order may differ, but the question asks whether two strings contain exactly the same characters with the same multiplicities.
Keep true
After each Counter scan step, the visible count for a character equals its occurrences in the processed prefix; complete equal maps are necessary and sufficient for anagrams.
Reuse it
Replace irrelevant order with a canonical frequency summary; the same idea supports ransom-note checks, multiset equality, permutation detection, and histogram comparison.
Read it this way: Counter starts with no entries for either string; the divider separates first="aab" from second="aba". Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Frequency map.
Simple idea: Anagrams have the same letter count. Counter builds that count map.