loading...

Leetcode - Contains Duplicate (with JavaScript)

urfan profile image Urfan Guliyev ・1 min read

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();
};

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++) {
    }
};

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

Posted on by:

urfan profile

Urfan Guliyev

@urfan

Love coding, eating and travelling

Discussion

markdown guide