Overview
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
Implement isAnagram(s, t).
Constraints
1 ≤ s.length, t.length ≤ 50000sandtconsist of lowercase English letters only.- Aim for $O(n)$ time, $O(1)$ space (the char frequency map has at most 26 entries).
Examples
isAnagram("anagram", "nagaram");
// → true
isAnagram("rat", "car");
// → false
isAnagram("listen", "silent");
// → trueNotes
- If lengths differ, immediately return false.
- Count character frequencies for
s, then decrement fort. If any count goes below 0, return false. - Alternatively, count both and compare.
Solution
Reveal solution
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = new Array(26).fill(0);
const aCode = 'a'.charCodeAt(0);
for (let i = 0; i < s.length; i++) {
counts[s.charCodeAt(i) - aCode]++;
counts[t.charCodeAt(i) - aCode]--;
}
return counts.every(c => c === 0);
}Resources
string-anagram.js
String Anagram
easycodingAlgorithmsStrings
Overview
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
Implement isAnagram(s, t).
Constraints
1 ≤ s.length, t.length ≤ 50000sandtconsist of lowercase English letters only.- Aim for $O(n)$ time, $O(1)$ space (the char frequency map has at most 26 entries).
Examples
isAnagram("anagram", "nagaram");
// → true
isAnagram("rat", "car");
// → false
isAnagram("listen", "silent");
// → trueNotes
- If lengths differ, immediately return false.
- Count character frequencies for
s, then decrement fort. If any count goes below 0, return false. - Alternatively, count both and compare.
Solution
Reveal solution
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = new Array(26).fill(0);
const aCode = 'a'.charCodeAt(0);
for (let i = 0; i < s.length; i++) {
counts[s.charCodeAt(i) - aCode]++;
counts[t.charCodeAt(i) - aCode]--;
}
return counts.every(c => c === 0);
}Resources
NameTopicDifficulty
103 of 103 problems