Intuition
Two strings are anagrams exactly when they have identical letter counts. Tally the counts of s, then subtract using t; if any count goes negative or lengths differ, they aren't anagrams.
Explanation
Idea
An anagram uses the same multiset of letters. So s and t are anagrams if and only if every character appears the same number of times in both. Counting is O(n) and beats sorting's O(n log n).
Algorithm
- If
len(s) != len(t), they can't be anagrams — returnfalse. - Build a frequency map
countsfroms(counts[c] += 1). - Walk
t: for each characterc, ifcounts[c]is already 0 (or missing) thenthas a lettersdoesn't have enough of → returnfalse; otherwisecounts[c] -= 1. - If we finish without a shortfall, return
true.
Worked example: s = "anagram", t = "nagaram"
Counts of s: a:3, n:1, g:1, r:1, m:1. Subtracting each letter of nagaram: n→a:3,n:0; a→a:2; g→g:0; a→a:1; r→r:0; a→a:0; m→m:0. Every count lands exactly at 0 with no shortfall → true.
Contrast s = "rat", t = "car": counts of rat = r:1,a:1,t:1. Subtracting car: c isn't in the map → return false.
Complexity
- Time: O(n) — two linear passes.
- Space: O(1) — at most 26 lowercase letters.
Implementation
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']++;
}
for (int i = 0; i < t.length(); i++) {
if (counts[t.charAt(i) - 'a'] == 0) {
return false;
}
counts[t.charAt(i) - 'a']--;
}
return true;
}
}