Valid Anagram
Pattern: Anagrams
Two strings are anagrams when every letter appears equally often in both. One array of 26 counts, +1 for each letter of s and -1 for each letter of t, must end all zeros.
The problem
Given two strings s and t of lowercase letters, return true if t is an anagram of s: it uses exactly the same
letters, each the same number of times. For example, "anagram" and "nagaram" give true, and "rat" and "car"
give false.
The function name isAnagram matches LeetCode. Use the link above for the exact statement and limits.
Think first
- What quick check rules out many pairs at once?
- How can one array track two strings at the same time?
- What should every count be at the end?
Hints
Brute force, and why it fails
Sort both strings and compare: O(n log n). For each letter of s, find and remove a matching letter in t: O(n²).
Counting is O(n).
The key insight
An anagram is the same bag of letters. A count per letter describes the bag completely, and the difference of two bags is zero exactly when they are equal.
Dry run
s = rat and t = car. The lengths match, so count. Each letter of s adds 1 and each letter of t takes 1 away.
The plan
if len(s) != len(t): return false
count = 26 zeros
for i from 0 to n - 1:
count[s[i]] = count[s[i]] + 1
count[t[i]] = count[t[i]] - 1
return every count is 0
Complexity
- Time
O(n)- Space
O(1)
One pass, and the 26 counts do not grow with n.
Edge cases
- Different lengths: false at once.
- Same string: true.
- Repeated letters, as in
"aacc"and"ccac": false, because the counts ofaandcdiffer.
I've built my logic, show the code
Java
class Solution {
public 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']++; // s adds one
count[t.charAt(i) - 'a']--; // t takes one away
}
for (int c : count) if (c != 0) return false;
return true;
}
}C++
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int count[26] = {0};
for (size_t i = 0; i < s.size(); i++) {
count[s[i] - 'a']++; // s adds one
count[t[i] - 'a']--; // t takes one away
}
for (int c : count) if (c != 0) return false;
return true;
}
};Python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for a, b in zip(s, t):
count[ord(a) - ord("a")] += 1 # s adds one
count[ord(b) - ord("a")] -= 1 # t takes one away
return all(c == 0 for c in count)Common mistakes
- Comparing sets of letters, which ignores counts.
- Forgetting the length check when counting only one string's letters.
- Using a 26-slot array for text that may contain other characters (LeetCode's follow-up asks about Unicode).