Anagram check with a frequency array
JavaScriptfunction isAnagram(s, t) {
if (s.length !== t.length) return false;
const freq = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
freq[s.charCodeAt(i) - 97]++;
freq[t.charCodeAt(i) - 97]--;
}
return freq.every((count) => count === 0);
}
console.log(isAnagram("listen", "silent"));
console.log(isAnagram("hello", "world"));Explanation
The array tracks how many times each lowercase letter appears. Characters from the first string increase the count, and characters from the second string decrease it. If both strings contain the same letters with the same frequency, every count finishes at zero.
Output
true false
Real-life Example
A puzzle or word-game app can check whether two guessed words contain exactly the same letters in a different order.