DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

Leetcode - Contains Duplicate (with JavaScript)

Today I am going to show how to solve the Leetcode Contains Duplicate algorithm problem.

Here is the problem:
Alt Text

Solution:
I use a hash table for solving this problem. In the hash table I’m going to map each element (as a key) to its index (as a value).

1) For creating a hash table, I’m using a new data structure called Map, which was introduced in ECMAScript 2015.

var containsDuplicate = function(nums) {
    let map = new Map();
};
Enter fullscreen mode Exit fullscreen mode

2) Next, I iterate through all of the numbers using for loop.

var containsDuplicate = function(nums) {
    let map = new Map();

    for (let i = 0; i < nums.length; i++) {
    }
};
Enter fullscreen mode Exit fullscreen mode

3) While I iterate the elements, I also check if the current element already exists in the table. If it exists, the function will break out of the loop and return true. Otherwise, I insert an element into the table.

var containsDuplicate = function(nums) {
    let map = new Map();

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

    return false
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
pgrekovich profile image
Pasha Grekovich

I have way simpler solution:

var containsDuplicate = function(nums) {
  const m = new Set(nums)
  return m.size === nums.length ? false : true
};
Enter fullscreen mode Exit fullscreen mode