I was studying some solutions to common algorithms and I ran across something that I am curious about. I tried to find the answer myself by googling and looking at some of the specifications but I am unable to find the answer to my question. The below algorithm basically checks to see if every item in the first array has a corresponding item squared in the second array. The naive solution (as they say) would have some sort of nested loop and be considered O(n2). The person who wrote the solution below said this is O(n).
I don't understand how this can be O(n) because he is using the Javascript "in" operator inside of his loop. As far as I can tell that operator checks to see if the value it's comparing exists in the object. How does it do that if it is not looping through the object under the hood? Is this really a linear time complexity?
function same(arr1, arr2) {
if (arr1.length !== arr2.length) {
return;
}
let frequencyMap1 = {};
let frequencyMap2 = {};
for (let val of arr1) {
frequencyMap1[val] = (frequencyMap1[val] || 0) + 1;
}
for (let val of arr2) {
frequencyMap2[val] = (frequencyMap2[val] || 0) + 1;
}
for (let key in frequencyMap1) {
if (!(key ** 2 in frequencyMap2)) {
return false;
}
if (frequencyMap2[key ** 2] !== frequencyMap1[key]) {
return false
}
}
return true;
}
console.log(same([1, 2, 3], [1, 4, 9])); // true