Contains Duplicate | LeetCode 217

This question asks you to determine if an array contains any duplicates.

The array [1, 2, 1] does contain a duplicate — the number 1 is repeated. On the other hand, the array [4, 3, 6] does not have any duplicates since no numbers are repeated.

The key to solving this problem is to loop over every element in the array. While on that element, check if we’ve seen it before. How do we know if we’ve seen that number before? We can use a data structure called a set to save the elements we’ve seen.

Let’s get to the code.

First, we create the set.

let numbers = new Set();

Then we need a loop to iterate over the elements.

for (let num of nums) {

}

Inside of that loop, we check if it’s the first time we’re seeing the number. If it is, we add it to the set.

for (let num of nums) {
    if (!numbers.has(num)) { // check if the number is not in the set
        numbers.add(num); // add to the set since it's the first time we're seeing it
    }
}

If it is already in the set, it means it’s a duplicate. Since it’s a duplicate, we just return true, meaning it’s *true* that the array contains a duplicate.

for (let num of nums) {
    if (!numbers.has(num)) {
        numbers.add(num);
    } else {
        return true; // since we found it in the set, return true
    }
}

However, if we’ve finished looping over all of the elements in the array, it means there are no repeated numbers, so we just return false, meaning it is *false* that there are duplicates in the array.

return false; // we've checked every element and none are already in the set, so there are no duplicates

And that’s it! The full implementation is at the bottom of this page, but if you want to support us and are interested in the resources we use to make this content, check out the links below.

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard


Last, but not least, here is the full implementation.

/**
 * @param {number[]} nums
 * @return {boolean}
 */
let containsDuplicate = function(nums) {
  let numbers = new Set();

  for (let num of nums) {
    if (!numbers.has(num)) {
      numbers.add(num);
    } else {
      return true;
    }
  }

  return false;
};