Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Are two words anagrams?

Easy · Target 10 minutes · Arrays and hashing· Type asked at

You're given two strings s and t made of lowercase English letters. Return true if t uses exactly the same letters as s, with each one turning up the same number of times, and false if it doesn't.

Examples

InputOutputWhy
s = "anagram", t = "nagaram"true
s = "rat", t = "car"false
s = "aab", t = "abb"falseThey've got the same letters, but not the same number of each.

Constraints

  • 0 ≤ s.length, t.length ≤ 5 × 10⁴
  • s and t contain only the letters a to z

Hints

Hint 1

If you sort both strings and compare them, that works in O(n log n). What does sorting tell you that you don't need to know?

Hint 2

Count how often each letter turns up in s, then do the same for t, and compare the two lots of counts.

Hint 3

You can get away with one table. Add 1 for each letter of s and take 1 off for each letter of t, and if they're anagrams you'll be left with 0 everywhere.

Where people lose marks

  • Comparing the sets of letters. "aab" and "abb" have the same set, but you'll see they don't have the same counts.
  • Building two tables and comparing them key by key, and then missing a letter that's in only one of them.
  • Leaving out the length check. The table on its own still gets it right, so this won't cost you the answer, but you've thrown away an early exit that's free.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.