Valid Anagram (LeetCode 242): Solution and Explanation

Easy
Hash Table
String
Sorting

Given two strings s and t, decide whether t is a rearrangement of s, meaning both strings use exactly the same characters with exactly the same counts.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Two strings are anagrams when one can be shuffled into the other. Shuffling changes positions but never changes how many times each character appears, so the real test is whether both strings have identical character counts. Position is irrelevant, which immediately rules out any approach that compares strings index by index.

One way to throw position away is to sort both strings. If they are anagrams, sorting puts them in the same canonical order and they become equal. That is easy and correct, but sorting costs O(n log n). Counting is cheaper. Build a frequency table for each string in a single pass, then compare the tables. Two strings with equal tables must be anagrams, and two anagrams must produce equal tables.

Before doing any counting there is a free shortcut. If the lengths differ, the strings cannot possibly be anagrams, so return false right away. Once the lengths are known to match, you can fill both count maps in the same loop using index i for both strings. The final comparison countS == countT checks that the maps have the same keys with the same values, which is exactly the anagram condition.

It also helps to see why this beats the brute force of searching t for each character of s and crossing it off. That approach rescans t for every character, which is O(n²). Counting reads each string exactly once, and the comparison at the end touches only the distinct characters, which for lowercase English text is never more than 26 entries per map.

Approach: Character frequency maps

  1. If len(s) != len(t), return False immediately.
  2. Create two empty dictionaries, countS and countT.
  3. Loop i over the indices of s. Increment countS[s[i]] and countT[t[i]] using get with a default of 0.
  4. After the loop, return whether countS == countT.

Step-by-step example

s = "aab", t = "aba"
  1. Both strings have length 3, so continue.
  2. i = 0: s[0] = 'a', t[0] = 'a'. countS = {a: 1}, countT = {a: 1}.
  3. i = 1: s[1] = 'a', t[1] = 'b'. countS = {a: 2}, countT = {a: 1, b: 1}.
  4. i = 2: s[2] = 'b', t[2] = 'a'. countS = {a: 2, b: 1}, countT = {a: 2, b: 1}.
  5. The two maps are equal, so return True.

Code: Python, Java, C++

1class Solution:
2    def isAnagram(self, s: str, t: str) -> bool:
3        if len(s) != len(t):
4            return False
5        countS, countT = {}, {}
6        for i in range(len(s)):
7            countS[s[i]] = 1 + countS.get(s[i], 0)
8            countT[t[i]] = 1 + countT.get(t[i], 0)
9        return countS == countT

Time and space complexity

Time

O(n)

One pass over n characters does two constant time dictionary updates per index. Comparing the two maps costs O(k), where k is the number of distinct characters, and k is at most n.

Space

O(k)

Each map holds one entry per distinct character. For lowercase English letters that is at most 26, so it is effectively O(1); for arbitrary Unicode it grows with the alphabet in use. The two input strings themselves are not copied.

Other approaches

Sort both strings (time O(n log n), space O(n))

Return sorted(s) == sorted(t). It is the shortest solution and fine in interviews when brevity matters, but sorting costs O(n log n) and builds new arrays.

Single fixed-size count array (time O(n), space O(1))

For lowercase letters only, use one array of 26 integers. Increment for characters of s and decrement for t, then check that every entry is zero. It avoids hashing and uses constant memory.

Common mistakes

  • Skipping the length check and then indexing t[i] while looping over s. If t is shorter, this raises an index error; if it is longer, the extra characters are never counted.
  • Using a set instead of a count. "aab" and "abb" have the same set of letters but are not anagrams.
  • Assuming only lowercase letters when the input may contain Unicode. A 26-slot array breaks on other characters, while the dictionary approach handles any character.
  • Decrementing in a single map and returning false only when a count goes negative, without checking the lengths first. Strings like "ab" and "a" would then incorrectly pass.

Frequently asked questions

What is the time complexity of Valid Anagram?

The counting approach runs in O(n) time because it reads each character once. Sorting both strings is O(n log n).

How do you handle Unicode characters?

Use a hash map keyed by character instead of a fixed array of 26 counters. The dictionary solution shown here already works for any characters.

Is sorting or counting better for anagram checks?

Counting is asymptotically faster and is the expected answer. Sorting is acceptable for short strings and is easier to write in one line.

Can I solve it with one hash map instead of two?

Yes. Increment counts for s and decrement for t in the same map, then confirm every value is zero. It saves a little memory but has the same complexity.