Skip to content

Valid Anagram

Check whether two strings use exactly the same letters the same number of times, with 26 counters.

EasyHashing
Solve on LeetCode

The problem

You get two strings s and t made of lowercase English letters. Return true if t is an anagram of s, meaning it uses exactly the same letters, each the same number of times, in any order. Otherwise return false.

Input s = "dosa", t = "soda"

Output true

Both use one d, one o, one s and one a.

Input s = "paneer", t = "pander"

Output false

Same length, but s has two e's and no d.

Key constraint: Each string can be up to 50,000 characters and holds only lowercase English letters, so 26 counters are enough.

How to spot the pattern

  • Order doesn't matter; only how many times each character appears.
  • The alphabet is small and fixed (26 lowercase letters), so counting is cheap.

The idea

Two strings are anagrams exactly when every letter appears the same number of times in both. So count the letters of s up and the letters of t down, and check that every count ends at zero. With only 26 possible letters, an array of 26 counters does the job of a hash map.

Brute force: Sort both strings and compare them, which takes O(n log n) time.

Step by step

  1. 1If the lengths differ, return false straight away.
  2. 2Make an array of 26 zeros, one counter per letter.
  3. 3Walk both strings together: add 1 for the letter of s and subtract 1 for the letter of t at each position.
  4. 4If any counter is not zero at the end, return false; otherwise return true.

See the pattern move

The hashing pattern on a small example. Step through it, or press play.

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        counts = [0] * 26  # one counter per letter
        for a, b in zip(s, t):
            counts[ord(a) - ord("a")] += 1
            counts[ord(b) - ord("a")] -= 1
        return all(c == 0 for c in counts)

Complexity

Time

O(n)

Space

O(1)

One pass over both strings; the 26 counters take the same space however long the strings are.

Watch out for

  • Skipping the length check: the shared loop then stops at the shorter string and never counts the extra letters of the longer one.
  • Comparing sets of letters instead of counts: "aab" and "abb" have the same set of letters but are not anagrams.

Follow-up questions

What if the strings can contain any Unicode characters?

Swap the 26-slot array for a hash map from character to count; the idea stays the same. In Java and JavaScript, also take care with characters that take two code units, such as emoji.

How would you group a whole list of words by anagram?

Give every word a key that its anagrams share, such as its sorted letters or its 26 counts, and collect the words in a map from key to list. That is Group Anagrams.

In Hinglish

Order bhool jao, sirf ginti dekho: s ke letters plus karo, t ke minus, aur end mein saare counters zero hone chahiye.

Related problems