2

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.

Eugene Ganshin
  • 125
  • 1
  • 10
  • 1
    In the first example you are `return`ing in the `findDuplicates` function, stopping it immediatly. In the second one, you are `return`ing in the `forEach`, which does not stop the other iterations from running (and it's useless to `return` a value in a `forEach`, as it won't be usable anywhere) – blex Jan 06 '21 at 20:26
  • 1
    Use `for (const el of nums) {` instead. Also I would recommend a `Set` instead of that `hash = {}`. – Bergi Jan 06 '21 at 20:28
  • ... or, using [`every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every), simply `return nums.every((el, i) => nums.indexOf(el) === i);` (without any `for` or `forEach`) – blex Jan 06 '21 at 20:31
  • @blex what's bigO of this function? using hash = {} makes it O(n) – Eugene Ganshin Jan 07 '21 at 22:21
  • I have no idea how to calculate that, but yes, using this will be less efficient than storing the encountered values in a `hash` variable (for `every` element, it will execute `indexOf`, which will internally loop too). Won't matter in most everyday uses (it makes the code easier to read IMO, and the time difference won't be noticeable), but if you have huge datasets it will indeed have an impact – blex Jan 07 '21 at 22:26

1 Answers1

1

Return statement is equivalent of break, for loop can be broken, foreach can't be.

Ravindra
  • 142
  • 2
  • 11
  • _"foreach can't be"_. That's not true. You can stop a `forEach` from looping (even though it's ugly): https://jsfiddle.net/pug02knh/ – blex Jan 06 '21 at 20:35
  • Refer this answer: https://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach – Ravindra Jan 06 '21 at 20:37
  • Exactly. My method is like the second example in the provided answer – blex Jan 06 '21 at 20:38