Valid Anagram

25 min · isAnagram()

Two word-game tiles can look unrelated until you sort the letters in your hand.

An anagram is a rearrangement that uses every original character exactly once. Given two strings s and t, return true when t is an anagram of s; otherwise, return false.

Think in terms of a multiset: a collection where both the values and their repeat counts matter. Order doesn't matter, but losing one a or gaining one z does.

A few ground rules:

  • Both strings contain lowercase English letters only.
  • Different lengths can never form an anagram pair.
  • Repeated letters must appear the same number of times in both strings.

Constraints

  • 1 <= s.length, t.length <= 50_000
  • s and t consist only of lowercase English letters a through z.

Hints

Make order disappear

If you sort both strings, anagrams collapse to the same ordered sequence of letters. This gives you a clean baseline solution.

Count instead of sorting

There are only 26 possible characters. Give each letter a counter, add the letters from s, then subtract the letters from t.

What must remain?

First reject unequal lengths. After all additions and subtractions, every one of the 26 counters must be zero.

Follow-up

Can you solve it with one fixed 26-slot table, no matter how long the two strings become?

Visible cases

Examples

Example 1

ready
Input
s = "secure"
t = "rescue"
Expected
true
Why
both words use the same six letters

Example 2

ready
Input
s = "letter"
t = "teller"
Expected
false
Why
the strings are equally long, but their letter counts differ

Example 3

ready
Input
s = "note"
t = "notes"
Expected
false
Why
an extra character makes the lengths differ

Interview signal

Asked at

AmazonBloombergUber
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite