Valid Anagram, Explained Properly: Sorting vs. Counting

Valid Anagram, Explained Properly: Sorting vs. Counting

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.

ApproachTime Complexity
Sort and compareO(n log n)
Frequency countingO(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

Tech Contributors

Written by

Tech Contributors

Digital expert at Tech Contributors, sharing insights on web development, SEO, and digital marketing.

View all posts
Share this article:

Frequently Asked Questions

Given two strings, determine whether one is an anagram of the other — meaning both contain exactly the same letters, with the same frequency of each, just arranged in a different order.

Sorting both strings and comparing them works and is easy to write, but it costs O(n log n) due to the sorting step. A frequency-counting approach using a dictionary can solve the same problem in O(n), a single pass through each string.

An ordering question asks whether elements appear in a specific sequence relative to each other. A counting question only asks how many times something occurs, regardless of order. Valid Anagram is fundamentally a counting question, which is why frequency counting is the more direct — and faster — fit.

Yes — checking the lengths first is a quick early exit. If the lengths differ, the strings cannot be anagrams, so there's no need to build or compare a frequency count at all.

The basic version shown assumes case-sensitive, space-free input. To handle real-world text, you'd typically normalize the strings first — converting to lowercase and removing spaces — before building the frequency count.

Got a website problem like this?

Whether it's a new build, a fix, or ongoing maintenance — tell us what you're dealing with and we'll tell you honestly what it'll take.