DEV Community

Cover image for JavaScript LeetCode Contains Duplicate
Diego (Relatable Code)
Diego (Relatable Code)

Posted on • Originally published at relatablecode.com on

JavaScript LeetCode Contains Duplicate

Introduction

Continuing through the problems of LeetCode. I am not haphazardly selecting any questions. I am following along with this list for those that were curious:

techinterviewhandbook.org/best-practice-que..

Prompt

Given an integer array nums , return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1] 
Output: true
Enter fullscreen mode Exit fullscreen mode

At first glance, the problem seems to be pretty simple. The idea here is to iterate over the array and find any duplicates. There’s a bit of a cheat code we can use with JavaScript in this one.

First Solution (cheating)

There is a standard built-in object for JavaScript called Set

But what does this object do?

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

Knowing this, the only thing we need to do is convert our array into a Set and compare its length with the original number array length.

var containsDuplicate = function(nums) {
    const set = new Set([...nums]);
    return set.size != nums.length;
};
Enter fullscreen mode Exit fullscreen mode

Converting an array into a Set is simple, just spread it into a new array in the Set constructor. It has a property to calculate the size (number of items). We just have to compare that with the length of the original array, nums.

return set.size != nums.length;
Enter fullscreen mode Exit fullscreen mode

Second Solution

Much like our (first solution) we can create a hash table of our array as we’re iterating and evaluate it in place.

var containsDuplicate = function(nums) {
   const hashTable = new Map();

    for(let i = 0; i < nums.length; i++) {
        if(hashTable.has(nums[i])) return true;
        else hashTable.set(nums[i], true);

    }
    return false;
};
Enter fullscreen mode Exit fullscreen mode

To break this down a little bit: we first iterate over the array of numbers. If the map already has the value then we return true. We check this with the .has property of map s

if(hashtable.has(nums[i]) return true;
Enter fullscreen mode Exit fullscreen mode

Otherwise, we add it to the map and move on.

else hashTable.set(nums[i], true);
Enter fullscreen mode Exit fullscreen mode

The value is pretty irrelevant as we don’t really care much for it. There probably is a data structure more suited here.

Let’s connect

More content at Relatable Code

If you liked this feel free to connect with me on LinkedIn or Twitter

Check out my free developer roadmap and weekly tech industry news in my newsletter.

Top comments (0)