Valid Anagram of Another String
Problem
Two strings are anagrams when one is a rearrangement of the other — same letters, same counts. Decide whether the inputs are anagrams using O(1) extra space if the alphabet is fixed.
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.
Input
s = "listen", t = "silent"Output
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;
}