loop | function isAnagram(a, b) {
if (a.length !== b.length) return false;
const aChars = a.split('').sort();
const bChars = b.split('').sort();
for (let ix = 0; ix < aChars.length; ix++) {
if (aChars[ix] !== bChars[ix]) return false;
}
return true;
}
isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
| ready |
join and compare | function isAnagram(a, b) {
if (a.length !== b.length) return false;
return a.split('').sort().join('') === b.split('').sort().join('');
}
isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
| ready |
hashmap | function isAnagram(left, right) {
const leftChars = new Map();
for (const leftChar of left) {
if (!leftChars.has(leftChar)) {
leftChars.set(leftChar, 0);
}
leftChars.set(leftChar, leftChars.get(leftChar) + 1);
}
for (const rightChar of right) {
if (!leftChars.has(rightChar)) {
return false;
}
leftChars.set(rightChar, leftChars.get(rightChar) - 1);
}
return [...leftChars.values()].every(val => val === 0);
}
isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
| ready |