Valid Anagram (LeetCode 242): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- If
len(s) != len(t), returnFalseimmediately. - Create two empty dictionaries,
countSandcountT. - Loop
iover the indices ofs. IncrementcountS[s[i]]andcountT[t[i]]usinggetwith a default of 0. - After the loop, return whether
countS == countT.
Step-by-step example
s = "aab", t = "aba"
- Both strings have length 3, so continue.
- i = 0: s[0] = 'a', t[0] = 'a'. countS = {a: 1}, countT = {a: 1}.
- i = 1: s[1] = 'a', t[1] = 'b'. countS = {a: 2}, countT = {a: 1, b: 1}.
- i = 2: s[2] = 'b', t[2] = 'a'. countS = {a: 2, b: 1}, countT = {a: 2, b: 1}.
- 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 == countT1class Solution {
2 public boolean isAnagram(String s, String t) {
3 if (s.length() != t.length()) return false;
4 int[] count = new int[26];
5 for (char c : s.toCharArray()) {
6 count[c - 'a']++;
7 }
8 for (char c : t.toCharArray()) {
9 count[c - 'a']--;
10 if (count[c - 'a'] < 0) return false;
11 }
12 return true;
13 }
14}1class Solution {
2public:
3 bool isAnagram(string s, string t) {
4 if (s.length() != t.length()) return false;
5 vector<int> count(26, 0);
6 for (char c : s) count[c - 'a']++;
7 for (char c : t) {
8 count[c - 'a']--;
9 if (count[c - 'a'] < 0) return false;
10 }
11 return true;
12 }
13};Time and space complexity
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.
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 overs. Iftis 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.