Valid Anagram
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Understand the problem
What is an anagram? A word you get by shuffling the letters of another word, using every letter exactly once. Nothing added, nothing left out.
listen→silent: same six letters (e,i,l,n,s,t), just in a different order.night→thing: same five letters.
So the question is really: do both strings contain exactly the same letters, the same number of times? The order doesn't matter at all.
Example 1
Input: s = "listen", t = "silent"
Output: trueBoth strings have one each of e, i, l, n, s, t.
Example 2
Input: s = "rat", t = "car"
Output: falsecar has a c, and rat doesn't. (And rat has a t that car doesn't.)
Example 3
Input: s = "aab", t = "abb"
Output: falseSame set of letters (a and b), but different counts: s has two as, t has only one. Counts matter, not just which letters appear.
Constraints
0 <= s.length, t.length <= 5 * 10^4sandtcontain lowercase English letters only.
Note
Follow-up: what changes if the strings may contain any Unicode character, like emoji?
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Count how many times each letter appears in both strings. If every count matches, they're anagrams.
The naive approach (and why it's slow)
One idea: for each letter of s, find a matching letter in t and cross it out. Finding a letter means scanning t, so for strings of length n that's about n × n steps, which is O(n²).
A better and very common idea is to sort both strings and compare them: "listen" and "silent" both sort to "eilnst". That's correct and short, but sorting costs O(n log n). We can do better.
The key insight
Order doesn't matter, only counts do. So instead of rearranging letters, we keep a tally (a hash map from letter to count):
- Every letter of
sadds 1 to its count. - Every letter of
ttakes 1 away.
If the strings are anagrams, everything cancels out exactly. If t ever needs a letter that has run out, they're not.
Step by step
s = "aab", t = "aba" (same length, so we continue).
First, count the letters of s:
Letter of s | Tally afterwards |
|---|---|
a | { a: 1 } |
a | { a: 2 } |
b | { a: 2, b: 1 } |
Then take away the letters of t:
Letter of t | Count before | Enough left? | Tally afterwards |
|---|---|---|---|
a | 2 | Yes | { a: 1, b: 1 } |
b | 1 | Yes | { a: 1, b: 0 } |
a | 1 | Yes | { a: 0, b: 0 } |
We never ran out, so the answer is true. With t = "abb" instead, the last b would find a count of 0, so we'd return false right there.
Why is "never ran out" enough? Because we already checked that both strings have the same length. If t never takes more of any letter than s has, and the totals are equal, every count must end at exactly zero.
The code
The reference solution is below, with comments on every important line. The Python version uses Counter, a built-in tally: Counter("aab") is {'a': 2, 'b': 1}, and two Counters are equal when every count matches.
How fast is it?
- Time: O(n). We look at each letter once, and each map update takes one step.
- Memory: O(1). There are only 26 possible lowercase letters, so the map never holds more than 26 entries, no matter how long the strings are.
Common mistakes
- Checking only which letters appear.
"aab"and"abb"use the same letters but aren't anagrams. You need the counts. - Forgetting the length check. Without it,
s = "ab",t = "a"never runs out of letters, and you'd wrongly returntrue.
Going deeper
- A 26-slot array instead of a map: since there are only lowercase letters,
counts[letter - 'a']works like a map and is a bit faster. - Follow-up, Unicode: the 26-slot array no longer fits, but the hash map version works unchanged. In JavaScript, loop with
for...of(by code point), not by index, so emoji and other characters outside the Basic Multilingual Plane aren't split in half.
Reference solution
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
export default function isAnagram(s, t) {
// Different lengths can never hold the same letters.
if (s.length !== t.length) return false
// A tally: letter -> how many times it appears in s.
const counts = new Map()
for (const char of s) counts.set(char, (counts.get(char) ?? 0) + 1)
// Take each letter of t away from the tally.
for (const char of t) {
const count = counts.get(char) ?? 0
// t needs a letter that s doesn't have (or doesn't have enough of).
if (count === 0) return false
counts.set(char, count - 1)
}
// Same length and we never ran out, so every count ended at zero.
return true
}export default function isAnagram(s: string, t: string): boolean {
// Different lengths can never hold the same letters.
if (s.length !== t.length) return false
// A tally: letter -> how many times it appears in s.
const counts = new Map<string, number>()
for (const char of s) counts.set(char, (counts.get(char) ?? 0) + 1)
// Take each letter of t away from the tally.
for (const char of t) {
const count = counts.get(char) ?? 0
// t needs a letter that s doesn't have (or doesn't have enough of).
if (count === 0) return false
counts.set(char, count - 1)
}
// Same length and we never ran out, so every count ended at zero.
return true
}from collections import Counter
def is_anagram(s: str, t: str) -> bool:
# Counter builds a tally: Counter("aab") == {"a": 2, "b": 1}.
# Two tallies are equal only when every letter has the same count.
# The length check is a cheap early exit before counting.
return len(s) == len(t) and Counter(s) == Counter(t)