Valid Anagram
Easy · Arrays & hashing
Jump to codeGiven two lowercase English strings, determine whether their character counts are identical. The order of the characters does not matter.
Examples
Example 1
s = "anagram" t = "nagaram"
Output: true
Example 2
s = "rat" t = "car"
Output: false
Constraints
- s and t consist of lowercase English letters.
Need a hint?
Equal lengths are necessary, but not sufficient.
Asked in real interviews
Candidates reported versions of Valid Anagram from these company interviews. Some company questions are locked and open with Premium or XP.
- Implement anagram check and stable deduplicationGoogle
- Implement anagram check and odd-even linked listBloomberg
Solution approach
Reject unequal lengths. Increment a 26-entry frequency array for the first string and decrement it for the second. The strings are anagrams exactly when every count is zero. A map generalizes the approach to a larger alphabet.
Complexity
O(n) time and O(1) auxiliary space for a fixed alphabet.
Python reference solution
def isAnagram(s, t):
if len(s) != len(t):
return False
counts = [0] * 26
for a, b in zip(s, t):
counts[ord(a) - ord('a')] += 1
counts[ord(b) - ord('a')] -= 1
return all(count == 0 for count in counts)
JavaScript solution
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
counts[s.charCodeAt(i) - 97]++;
counts[t.charCodeAt(i) - 97]--;
}
return counts.every(count => count === 0);
}
Java solution
import java.util.*;
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
counts[s.charAt(i) - 'a']++;
counts[t.charAt(i) - 'a']--;
}
for (int count : counts) if (count != 0) return false;
return true;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
array<int, 26> counts{};
for (size_t i = 0; i < s.size(); i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
return all_of(counts.begin(), counts.end(), [](int count) { return count == 0; });
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "anagram", "nagaram" ]
true
[ "rat", "car" ]
false
[ "", "" ]
true
[ "aacc", "ccac" ]
false
[ "listen", "silent" ]
true
Drafts are saved per language in this browser when storage is available.