Closed
Description
Bug Report for https://neetcode.io/problems/duplicate-integer
Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.?title=Bug Report for is-anagram
Hi team, hash-map solution for JS doesn't cover scenario, where key length is equal, but some keys have different values
class Solution {
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
isAnagram(s, t) {
if (s.length !== t.length) {
return false;
}
const countS = {};
const countT = {};
for (let i = 0; i < s.length; i++) {
countS[s[i]] = (countS[s[i]] || 0) + 1;
countT[t[i]] = (countT[t[i]] || 0) + 1;
}
for (const key in countS) {
if (**countS[key]** !== **countT[key]**) {
return false;
}
}
return true;
}
e.g.
s="raceear" // {'r':2, 'a':2, 'c':1,'e':2}
t="carrace" // {'c':2, 'a':2, 'r': 2, 'e':1}
number of keys is the same, keys are same, but values of r and c are different
my not optimized solution is
isAnagram(s, t) {
if (s.length !== t.length) {
return false
}
const dict1 = s.split('').reduce((acc, char) => {
if (acc[char]) {
acc[char] += 1
} else {
acc[char] = 1
}
return acc
}, {})
const dict2 = t.split('').reduce((acc, char) => {
if (acc[char]) {
acc[char] += 1
} else {
acc[char] = 1
}
return acc
}, {})
if (Object.keys(dict1).length !== Object.keys(dict2).length) {
return false
}
for (const [entrySKey, entrySValue] of Object.entries(dict1)) {
const a = Object.entries(dict2)
const entryT = a.find(([entryTKey, _]) => {
console.log('entryTKey', entryTKey)
return entryTKey === entrySKey
})
if (!entryT) {
return false
}
if (entryT[1] !== entrySValue) {
return false
}
}
return true
}
Metadata
Metadata
Assignees
Labels
No labels