Valid Anagram — Solution in Python, Java & C++
Valid Anagram solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings and hash table.
Valid Anagram is an easy coding problem on strings, hash table and sorting, asked in Amazon, Infosys, Bloomberg and Uber interviews.
- Difficulty: Easy
- Topics: Strings, Hash Table, Sorting, Counting
- Asked at: Amazon, Infosys, Bloomberg, Uber, Yelp, Mindtree, Directi, Tech Mahindra
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given two strings s and t, return true if t is an anagram of s.
An anagram uses exactly the same letters with exactly the same multiplicities, rearranged.
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Example 3
Input: s = "aacc", t = "ccac"
Output: false
Explanation: Same letters, but the counts differ.
Constraints
1 <= s.length, t.length <= 40s and t consist of lowercase English letters.
Follow-up: What if the inputs contained Unicode characters instead of just 26 letters?
Hints for Valid Anagram
Hint 1
Different lengths can never be anagrams — check that first and return early.
Hint 2
Count each of the 26 letters in
s, then decrement while scanningt.Hint 3
The moment a count drops below zero,
thas a letterscannot supply.
How to solve Valid Anagram
Two strings are anagrams exactly when every letter occurs the same number of times in each. Count the letters of s, then let t consume them.
Approach
- Return
falseif the lengths differ. - Increment a 26-slot count for each letter of
s. - Decrement for each letter of
t; the moment a count goes negative, returnfalse. - Return
true.
Why it works
With equal lengths, if no count goes negative then t never uses a letter more often than s supplies it, and since the totals match no letter can be under-used either — the multisets are identical.
Complexity
- Time —
O(n) - Space —
O(1) — 26 counters
Pitfalls
- Sorting both strings and comparing is
O(n log n); correct but slower. - For Unicode inputs replace the fixed array with a hash map.
Reference solution
Python
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for ch in s:
count[ord(ch) - 97] += 1
for ch in t:
idx = ord(ch) - 97
count[idx] -= 1
if count[idx] < 0:
return False
return TrueJava
public static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
for (int i = 0; i < t.length(); i++) {
int idx = t.charAt(i) - 'a';
count[idx]--;
if (count[idx] < 0) return false;
}
return true;
}C++
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int count[26] = {0};
for (char ch : s) count[ch - 'a']++;
for (char ch : t) {
int idx = ch - 'a';
count[idx]--;
if (count[idx] < 0) return false;
}
return true;
}JavaScript
var isAnagram = function(s, t) {
if (s.length !== t.length) return false;
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) count[s.charCodeAt(i) - 97]++;
for (let i = 0; i < t.length; i++) {
const idx = t.charCodeAt(i) - 97;
count[idx]--;
if (count[idx] < 0) return false;
}
return true;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings · Hashing: Hash Maps and Hash Sets