Here's the simple LeetCode function to find duplicates in the given array.
function findDuplicates(nums) {
let hash = {}
for (let i = 0; i < nums.length; i++) {
if (!hash[nums[i]]) {
hash[nums[i]] = true
} else {
return true
}
}
return false
}
It works great. But what's going to happen if we switch to forEach method instead?
function findDuplicates(nums) {
let hash = {}
nums.forEach(el => {
if (!hash[el]) {
hash[el] = true
} else {
return true
}
});
return false
}
This function will not work with the same input of [0,4,5,3,0,6]
.
Could you please explain why these two solutions give different results? Or just point me to the right direction.