Algorithm Series — the Frequency Counter Pattern

//test cases for our function validAnagram('stressed', 'desserts') // true
validAnagram('nope', 'notanagram')// false
validAnagram('pup', 'puppy')// false
validAnagram('listen', 'silent') // true
function validAnagram(word1, word2){
if (word1.length !== word2.length){
return false
}

}
function validAnagram(word1, word2){
if (word1.length !== word2.length){
return false
}

let letterCounter1 = {}
let letterCounter2 = {}

for (const letter of word1){
letterCounter1[letter] = (letterCounter1[letter] || 0) + 1
}
for (const letter of word2){
letterCounter2[letter] = (letterCounter2[letter] || 0) + 1
}

}
//visualization purposes only letterCounter1 = {
s: 3,
t: 1,
r: 1,
e: 2,
d: 1
}
letterCounter2 = {
d: 1,
e: 2,
s: 3,
r: 1,
t: 1
}
function validAnagram(word1, word2){
if (word1.length !== word2.length){
return false
}

let letterCounter1 = {}
let letterCounter2 = {}

for (const letter of word1){
letterCounter1[letter] = (letterCounter1[letter] || 0) + 1
}
for (const letter of word2){
letterCounter2[letter] = (letterCounter2[letter] || 0) + 1
}
for (const letter in letterCounter1){
if (letterCounter1[letter] !== letterCounter2[letter]){
return false
}
}
return true
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store