0:00 / 0:00

Check if two words use exactly the same letters. Count up for every letter in one, count down for the other, and see if every tally hits zero.

▼

The problem

Given two strings s and t of lowercase letters, return true if t is an anagram of s: the same letters, each the same number of times, in any order.

Example: s = "anagram", t = "nagaram" gives true (three a's, one each of n, g, r, m on both sides).

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    count = [0] * 26
    for c in s:
        count[ord(c) - ord('a')] += 1
    for c in t:
        count[ord(c) - ord('a')] -= 1
    return all(x == 0 for x in count)
TRY IT ON LEETCODE ▶

The solution

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    count = [0] * 26
    for c in s:
        count[ord(c) - ord('a')] += 1
    for c in t:
        count[ord(c) - ord('a')] -= 1
    return all(x == 0 for x in count)

Transcript

Valid Anagram. You're given two strings, s and t. Is t an anagram of s? It must use exactly the same letters, each one the same number of times, in any order. Listen and silent, for example, are the same six letters, shuffled.

Take anagram and nagaram. Anagram has three a's, and one each of n, g, r and m. Nagaram has exactly the same counts, so the answer is true. But rat and car? Car has a c where rat has a t. False.

The easy way is to sort both strings and compare. Sorted, anagram and nagaram become the same string. It works, but sorting costs n log n. Checking every letter of s against all of t is even worse: n squared.

We can do better: just count. Picture a shelf of sweet jars, one for each letter, twenty six in all. Every letter of s drops a candy into its jar. Every letter of t takes one back out. If they're anagrams, every candy that goes in comes back out, and all the jars end up empty.

Let's run the example. Anagram fills the a jar to three, and the n, g, r and m jars to one each. Then nagaram takes them all out again. Every jar is back to zero, so it's true.

Now rat and car. Rat drops r, a and t. Car takes out c, a and r. The t jar still holds a candy, and the c jar goes below zero. A jar that isn't empty means false. And if the lengths differ, they can never match, so check that first.

In code: if the lengths differ, return false. Make twenty six counters, all zero. Add one for each letter of s, subtract one for each letter of t, and return whether every counter is zero.

Each string is read just once, so the time is order n. And there are always twenty six counters, at any length, so the space is order one.

Count up, count down, check for zero. That's Valid Anagram.