Foundations

Valid Anagram

Character frequency counting: two strings are anagrams when their character frequency dicts are equal.

easyFree~8 min

Problem

A spell-checker needs to verify that a user's retyped word is a valid rearrangement of the original. Given two strings s and t, return true if t is an anagram of s - that is, if t uses exactly the same characters as s, each the same number of times.

Input: s = "anagram", t = "nagaram"   → true
Input: s = "rat",     t = "car"       → false
Input: s = "ab",      t = "a"         → false  (different lengths)
Input: s = "",        t = ""          → true

Solution

Approach: frequency counting with Counter equality.

Two strings are anagrams exactly when they hold the same characters the same number of times - order is irrelevant. That definition is a statement about character frequencies, so the solution builds a frequency map for each string and compares the maps. First short-circuit on length: if len(s) != len(t) the strings cannot be anagrams, so return False before doing any counting. Then Counter(s) == Counter(t) builds both frequency dicts and compares them; dict equality checks that every key maps to the same count in both, which is precisely the anagram condition.

Counter is a dict subclass that tallies occurrences in one pass, so Counter("anagram") is {a:3, n:1, g:1, r:1, m:1}. Two strings produce equal counters if and only if they are anagrams, so the comparison is the whole answer. Trace s="rat", t="car": lengths match (3 == 3), Counter("rat") is {r:1,a:1,t:1} and Counter("car") is {c:1,a:1,r:1}; they differ on t versus c, so equality is False. The length guard is not strictly required for correctness - unequal counters already differ - but it lets obvious mismatches exit without building any maps.

Edge cases: two empty strings pass the length check (0 == 0) and have equal empty counters, returning True; same-length strings with different letters ("aab" vs "bba") differ in counts and return False.

Complexity: O(n) time, O(k) space - one pass per string to count; k distinct characters stored (at most 26 for lowercase English, effectively O(1)).

Done reading? Mark it so it sticks in your dashboard.

Next in CodingGroup Anagrams

Discussion (0)

Sign in to join the discussion.
No comments yet. Start the discussion.