[Array] #217 Contains Duplicate


Problem

Given an integer array nums,
return true if any value appears at least twice in the array,
and return false if every element is distinct.


My Solution

  • Runtime: 953 ms
  • Memory: 26 MB

    class Solution:
        def containsDuplicate(self, nums: List[int]) -> bool:
            if len(set(nums)) != len(nums):
                return True
            return False

Best Solution

  • Runtime: 588 ms
  • Memory: 25.9 MB

    class Solution:
        def containsDuplicate(self, nums: List[int]) -> bool:
            return len(set(nums)) != len(nums)

Time Complexity

  • Converting list to set: Iterating list O(n) + Putting element into set O(1) = O(n)
  • len(): O(1) (including both set and list length)


Reference

LeetCode 217. Contains Duplicate