Skip to content

LC 217. Contains Duplicate

mccornet edited this page Jul 25, 2021 · 7 revisions

217. Contains Duplicate

Solution

A Simple and fast way is to use a set. But instead of iterating over the set as in the first attempt it is faster to just compare set size to array size.

Python

class Solution:

    def containsDuplicate(self, nums: list[int]) -> bool:
        numbers_seen = set()
        
        for number in nums:
            if number in numbers_seen:
                return True
            else:
                numbers_seen.add(number)
        
        return False


    def containsDuplicate(self, nums: list[int]) -> bool:
        numbers_set = set(nums)
        return len(numbers_set) != len(nums)

JavaScript

Runtime: 72 ms, faster than 98.39%

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    const numbers_set = new Set(nums)
    return numbers_set.size !== nums.length
};

Clone this wiki locally