leetcode: Contains Duplicate : JavaScript submission 86%+ runtime

Posted on

I did leetcode’s “Contains Duplicate” problem and surprisingly got my runtime to beat 86.89% of other JavaScript solutions.

The code uses JavaScript’s Set object which “lets you store unique values of any type, whether primitive values or object references.” The premise of the solution is that every time a value appears, we check the set to see if it exists. If not we add it to the set. If it does exist we return a true, ending the program.

An additional note, the reason that forEach would not be a good choice is that you can’t return from a forEach. So if I found in index 1 that we have a duplicate, with a for loop we can return and the function does not need to iterate over n more elements. With a forEach we would have to wait until the end of the forEach when the answer is already known

var containsDuplicate = function(nums) {
    let set = new Set()
    for(i=0;i<nums.length;i++){
        if(set.has(nums[i])){return true}
        set.add(nums[i])
    }
    return false
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s