Valid Anagram
Easy
Topics
Given two strings s and t, return true if t is an anagram of s (same letters, same counts).
Example 1
s
t
Both strings use the same letters the same number of times, so the answer is
true.Rows are the two strings, character by character.
Input: s = "anagram", t = "nagaram" Output: true
Example 2
s
t
The shaded characters in
t have no counterpart left in s, so the answer is false. A length mismatch alone is already enough to decide it.Input: s = "rat", t = "car" Output: false
Constraints
- 1 <= s.length, t.length <= 5*10^4
- s and t consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two strings are anagrams exactly when they contain the same multiset of characters. Comparing their character-frequency counts settles it.
Approach
- Different lengths → not anagrams.
- Count characters of
s. - Decrement while scanning
t; a missing or over-used character means false. - If all counts balance, they are anagrams.
Walkthrough
s = "anagram", t = "nagaram"
count(s) = {a:3, n:1, g:1, r:1, m:1}
count(t) = {n:1, a:3, g:1, r:1, m:1} -> equal -> trueComplexity
- Time — O(n): counting both strings is linear.
- Space — O(1): the count map is bounded by the alphabet (26 lowercase letters).
Common Pitfalls
- For Unicode input, a fixed 26-size array no longer suffices — use a hash map.
Full Solution — all languages
class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False
counts = {}
for c in s:
counts[c] = counts.get(c, 0) + 1
for c in t:
if counts.get(c, 0) == 0:
return False
counts[c] -= 1
return Trueimport java.util.*;
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character, Integer> counts = new HashMap<>();
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
for (char c : t.toCharArray()) {
int left = counts.getOrDefault(c, 0);
if (left == 0) return false;
counts.put(c, left - 1);
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map<char, int> counts;
for (char c : s) counts[c]++;
for (char c : t) {
if (counts[c] == 0) return false;
counts[c]--;
}
return true;
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var isAnagram = function(s, t) {
if (s.length !== t.length) return false;
const counts = new Map();
for (const c of s) counts.set(c, (counts.get(c) || 0) + 1);
for (const c of t) {
const left = counts.get(c) || 0;
if (left === 0) return false;
counts.set(c, left - 1);
}
return true;
};