Skip to content

Instantly share code, notes, and snippets.

@iknowmagic
Created May 18, 2019 16:51
Show Gist options
  • Save iknowmagic/65194b7dab083af17363944075c13ac4 to your computer and use it in GitHub Desktop.
Save iknowmagic/65194b7dab083af17363944075c13ac4 to your computer and use it in GitHub Desktop.
Frequency Calculator #JavaScript
// O(n)
// two loops is better than nested loops
function same(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false
}
let frequencyCounter1 = {}
let frequencyCounter2 = {}
for (let val of arr1) { // of = value
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1
}
for (let val of arr2) {
frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1
}
console.log({frequencyCounter1, frequencyCounter2})
for (let key in frequencyCounter1) { // in = key
// do the keys match?
if (!(key ** 2 in frequencyCounter2)) {
return false
}
// does the value count match?
if (frequencyCounter2[key ** 2] !== frequencyCounter1[key]) {
return false
}
}
return true
}
same([1,2,2,3, 5], [9,1,4,4, 11])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment