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) {
if (left.length !== right.length) return false;
const charMap = new Map();
for (const leftChar of left) {
charMap.set(leftChar, (charMap.get(leftChar) || 0) + 1);
}
for (const rightChar of right) {
if (!charMap.get(rightChar)) return false;
charMap.set(rightChar, (charMap.get(rightChar) || 0) - 1);
}
return [...charMap.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 |
object-map | function isAnagram(left, right) {
if (left.length !== right.length) return false;
const charMap = {};
for (const leftChar of left) {
charMap[leftChar] = (charMap[leftChar] || 0) + 1;
}
for (const rightChar of right) {
if (!charMap[rightChar]) return false;
charMap[rightChar] = (charMap[rightChar] || 0) - 1;
}
return Object.values(charMap).every(v => v === 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 |