Leetcode - Contains Duplicate (with JavaScript)

urfan

Urfan Guliyev

Posted on June 28, 2020

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
šŸ’– šŸ’Ŗ šŸ™… šŸš©
urfan
Urfan Guliyev

Posted on June 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related