← Whiteboard questions

Valid Anagram

Check if two words are made of the same letters

DSA, Easy, Arrays & Hashing

Which structure or algorithm, and what does it cost.

You get two strings a and b of lowercase letters. Return true if you can reorder the letters of a to spell b, with no letter left over and none missing. Return false otherwise. Two empty strings match.

Examples

Input a = "stored", b = "dorset"
Output true
Why both words use the letters d, e, o, r, s and t once each.
Input a = "level", b = "bevel"
Output false
Why the lengths match, but a has two l letters and b has only one.
Input a = "", b = ""
Output true
Why no letters are needed on either side, so they match.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) extra memory, because the alphabet has 26 letters.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

If two words are rearrangements of each other, what must be true about how many times each letter appears in them?

Hint 2 the approach

Count the letters of the first word. Then walk the second word and spend those counts. What tells you the words do not match?

Hint 3 the key step

Check something cheap first. Then count a and spend the counts on b: what should happen when a count is already zero?

Walkthrough

Full walkthrough brute force to best

Brute force

Try every rearrangement of a and see if one equals b. A word with n letters has up to n factorial rearrangements, so even 12 letters is about 479 million tries. This is far too slow for 50,000 letters.

Better method

Sort the letters of both words and compare the two results. Rearrangements have the same sorted form. This is O(n log n) time and O(n) memory, and it is short to write. It is a fine answer when n is small.

Best method

Two words match exactly when they have the same length and the same count for every letter. Count the letters of a in a table. Then walk b and spend one from the table for each letter. If a letter has no count left, b has more of it than a, so the answer is false. Because the lengths are equal, finishing the walk without a failure means every count ended at zero, so the words match. The table has at most 26 entries, so the memory does not grow with the input.

Hand trace

Run on a = "stored", b = "dorset". The lengths are 6 and 6. Counting a gives s 1, t 1, o 1, r 1, e 1, d 1. Walk b. d has count 1, spend it, count 0. o: 1 to 0. r: 1 to 0. s: 1 to 0. e: 1 to 0. t: 1 to 0. No letter ran out, so the answer is true.

Code

def is_anagram(a, b):
    if len(a) != len(b):
        return False
    counts = {}
    for ch in a:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in b:
        if counts.get(ch, 0) == 0:
            return False
        counts[ch] -= 1
    return True

Time and memory

O(n) time, because each word is read once and each table step is O(1). O(1) extra memory, because the table holds at most 26 letters. A dictionary is fine. A list of 26 numbers is also fine.

Common mistakes

  • Comparing only the sets of letters. The words "aab" and "abb" use the same letters but are not rearrangements.
  • Skipping the length check and counting only one way. Without it, "ab" against "abc" passes when you only spend the letters of the shorter word.
  • Letting a count go below zero and reading it as a match. Stop and return false when a letter has no count left.

Related problems

More Arrays & Hashing problems
Valid Anagram: hints, walkthrough and Python solution