Valid Anagram

EasyHashing · Frequency Count🧩 Hashing & CountingLeetCode #242 ↗Updated

Problem

Given two strings s and t, decide whether t is a rearrangement of s: both must use exactly the same letters, each exactly the same number of times. Return true or false.
Inputs = "anagram", t = "nagaram"Outputtrue
Inputs = "rat", t = "car"Outputfalse
Inputs = "aab", t = "abb"Outputfalse (counts differ)

1 ≤ |s|, |t| ≤ 5·104  ·  lowercase English letters only  ·  Follow-up: what if the input holds Unicode?

Try it yourself

Java
class Solution {
    public boolean isAnagram(String s, String t) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Order does not matter, only how many of each letter. Add one per letter of s, subtract one per letter of t; the strings are anagrams exactly when every counter ends at zero.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceMatch & Cross Off

Time O(n2)Space O(n)

For every character of s, search t for an unused copy and mark it used. If any search fails, some letter is missing or short. Equal lengths plus every letter matched means a perfect pairing.

Java
public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    boolean[] used = new boolean[t.length()];
    for (int i = 0; i < s.length(); i++) {
        boolean found = false;
        for (int j = 0; j < t.length(); j++) {
            if (!used[j] && t.charAt(j) == s.charAt(i)) {
                used[j] = true; // cross this copy off
                found = true;
                break;
            }
        }
        if (!found) return false;
    }
    return true;
}

Mirrors how you'd check by hand, but each search is linear → quadratic.

At a glance

LevelApproachTimeSpace
Brute ForceMatch & Cross OffO(n2)O(n)
BetterSort Both StringsO(n log n)O(n)
Optimal26-Slot Counter ArrayO(n)O(1)
Common pitfalls
  • Skipping the length check — "ab" vs "abb" may slip through.
  • Comparing only the set of letters, not their counts ("aab" vs "abb").
  • Using int[26] when the input can contain uppercase or Unicode.
Interview tips
  • Clarify the alphabet first; it decides between an array and a hash map.
  • Mention the early exit: different lengths can never be anagrams.
  • Explain why O(26) counts as O(1) space.
Pattern
Frequency counting → when two collections must match as multisets regardless of order.
My notes saved in this browser