Valid Anagram
Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Walk both strings together: bump the counter for each character of the first string, drop it for each character of the second. If both strings are anagrams, every counter ends at zero.
s = "listen", t = "silent"truedef is_anagram(s, t):
if len(s) != len(t):
return False
count = [0] * 26
for cs, ct in zip(s, t):
count[ord(cs) - 97] += 1
count[ord(ct) - 97] -= 1
return all(c == 0 for c in count)
function isAnagram(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]++;
count[t.charCodeAt(i) - 97]--;
}
return count.every(function (c) { return c === 0; });
}
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']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}
}
bool isAnagram(const string& s, const string& t) {
if (s.size() != t.size()) return false;
int count[26] = {};
for (int i = 0; i < (int)s.size(); i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}
Explanation
Two strings are anagrams when they use the exact same letters the same number of times. The neat trick here is one counter array that goes up for s and down for t; if they match, everything cancels back to zero.
First a quick shortcut: if the lengths differ, they cannot be anagrams, so we return False immediately. Otherwise we make count = [0] * 26, one slot per lowercase letter, using ord(c) - 97 to turn a letter into its slot index (a→0, b→1, ...).
We walk both strings together with zip(s, t). For each pair we do count[...] += 1 for the character from s and count[...] -= 1 for the character from t. Every letter s adds, t must remove.
At the end we return all(c == 0 for c in count). If even one slot is non-zero, one string had a letter the other didn't, so they are not anagrams.
Example: s = "listen", t = "silent". They share the letters l, i, s, t, e, n once each, so every increment from s is undone by a decrement from t, leaving all zeros and the answer true.