Valid Anagram is one of those problems where the first solution that comes to mind also happens to work — which makes it easy to stop there without asking whether it’s actually the best fit.
The problem
Given two strings, determine if one is an anagram of the other: same letters, same frequency of each, just arranged differently.
s = "listen"
t = "silent"
# Expected output: True
The instinct: sort and compare
s = "listen"
t = "silent"
if sorted(s) == sorted(t):
print("Valid anagram")
else:
print("Not a valid anagram")
This works, and it’s genuinely a clean two-line solution. The reason it works: sorting forces matching letters to line up in the same positions. If two strings are anagrams, their sorted versions are character-for-character identical.
The catch is cost — sorting takes O(n log n). Fine for small inputs, but not optimal.
The reframe: this is a counting question, not an ordering question
Sorting solves the problem by imposing an order. But the actual question being asked — “do both strings contain the same letters the same number of times?” — has nothing to do with order at all. It’s a counting question. And counting is something a dictionary handles in a single pass, with no rearranging required.
def is_anagram(s, t):
if len(s) != len(t):
return False
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for char in t:
if char not in counts or counts[char] == 0:
return False
counts[char] -= 1
return True
The logic: build a frequency count from the first string, then walk through the second string subtracting from that same count. If a character is ever missing or already exhausted, the strings can’t be anagrams — return immediately, no wasted work.
| Approach | Time Complexity |
|---|---|
| Sort and compare | O(n log n) |
| Frequency counting | O(n) |
The pattern, again
This is the same dictionary tool from Two Sum, just answering a different kind of question — counting occurrences instead of remembering a position. The actual skill worth building isn’t memorizing this specific solution; it’s getting faster at recognizing which question a problem is really asking, since that determines which tool actually fits.
What’s next
This is Video 3 in Think in Patterns, Not Problems. Next video applies this same one-pass instinct to a new shape of problem.
Watch the full walkthrough: https://youtu.be/TYG5mnvV0FY
Full playlist: https://www.youtube.com/playlist?list=PLTyiXpqKeCvQ