Skip to content
mlmentorship

Valid Anagram

Check whether two strings contain the same letters with the same counts.

Published · 5 min read ·Core ·Foundation

30-second answer map

Visual first · depth when needed

Two strings are anagrams exactly when their character-count maps are equal.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Valid Anagram

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

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

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.

from collections import Counter

def is_anagram(first: str, second: str) -> bool:
   return Counter(first) == Counter(second)

Cost: time and space, where is the number of different characters.