Skip to content

Instantly share code, notes, and snippets.

@Jimmydalecleveland
Last active June 8, 2019 15:40
Show Gist options
  • Save Jimmydalecleveland/cca72563d531295a2fa2ad56b6fdd6df to your computer and use it in GitHub Desktop.
Save Jimmydalecleveland/cca72563d531295a2fa2ad56b6fdd6df to your computer and use it in GitHub Desktop.
Given 2 arrays, compare occurrences from the first array, squared, to the second array
// O(n^2)
// function same(arr1, arr2) {
// if (arr1.length !== arr2.length) return false
// let result = true;
// arr1.forEach((num) => {
// const currentIndex = arr2.indexOf(num * num)
// if (currentIndex === -1) {
// result = false
// } else {
// arr2.splice(currentIndex, 1)
// }
// })
// return result
// }
// O(n)
function same(arr1, arr2) {
if (arr1.length !== arr2.length) return false
const arr1Occurrences = {}
const arr2Occurrences = {}
for (const value of arr1) {
arr1Occurrences[value] = (arr1Occurrences[value] || 0) + 1
arr1Occurrences
}
for (const value of arr2) {
arr2Occurrences[value] = (arr2Occurrences[value] || 0) + 1
arr2Occurrences
}
for (const key in arr1Occurrences) {
if(!(key ** 2 in arr2Occurrences)){
return false
}
if (arr1Occurrences[key] !== arr2Occurrences[key ** 2]) {
return false
}
}
return true
}
same([1,2,3], [4,1,9])
same([1,2,3], [1,9])
same([1,2,1], [4,4,1])
same([3,1,1], [4,1,1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment