Skip to content
Ayotl

← All challenges

Interview challenge · easy · string, hash-map, sorting

Valid Anagram

The challenge

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

Example

"anagram", "nagaram"  ->  true
"rat", "car"          ->  false

Idea: count letters instead of sorting. Add one for each letter of s, subtract one for each letter of t; it is an anagram if every count ends at zero. Time O(n), space O(1) for a fixed alphabet.

The solution

# Valid Anagram - ayotl.dev
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    # +1 for letters of s, -1 for t
    count = {}
    for a, b in zip(s, t):
        count[a] = count.get(a, 0) + 1
        count[b] = count.get(b, 0) - 1
    # anagram: every count is back to 0
    return not any(count.values())


print(is_anagram("anagram", "nagaram"))
print(is_anagram("rat", "car"))

$ python3 valid_anagram.py

True

False

The video

Watch on YouTube →