in ,

Check if an Array Contains Duplicates

Before reading this post, I strongly suggest you watch the video above.

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.

/****please format like code****/

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    }}

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

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

And that’s it! I have many more solutions to algorithm questions on my YouTube channel Terrible Whiteboard. This is a good resource if you think your interview will give you an algorithm question to solve.

Anyway, here is the full implementation.

var containsDuplicate = function(nums) {
  let numbers = new Set();
  for (let num of nums) {
    if (!numbers.has(num)) {
      numbers.add(num);
    } else {
      return true;
    }  
  }  
  return false;
};

This post was created with our nice and easy submission form. Create your post!

What do you think?

Written by Terrible Whiteboard

If you like this content, check out my YouTube channel Terrible Whiteboard at https://www.youtube.com/channel/UCpLC2ohmappF2iUsWYRnsxg. I post answers to algorithm questions and web development tips and tricks multiple times a week.

adonis-mysql-error

Adonis JS No MYSQL Module Error Fix

Strange Phrases You Might Hear at Your Software Job