Skip to content

217. Contains Duplicate

Problem Statement

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.

Examples

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints

  • 1<= nums.length <=105
  • 109<= nums[i] <=109

Submissions

python
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums))
python
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        seen = set()
        for num in nums:
            if num in seen:
                return True
            seen.add(num)
        return False

Explanations

Python
Submitted by @noeyislearning
  • class Solution:: This is the class that contains the function containsDuplicate.
  • def containsDuplicate(self, nums: List[int]) -> bool:: This function takes in a list of integers nums and returns a boolean value.
  • return len(nums) != len(set(nums)): This line of code checks if the length of the list nums is not equal to the length of the set of nums. If the lengths are not equal, it means that there are duplicates in the list, so the function returns True. Otherwise, it returns False.
    • len(nums): This returns the length of the list nums.
    • set(nums): This converts the list nums into a set, which removes duplicates. The length of the set will be less than the length of the list if there are duplicates.
Python
Submitted by @noeyislearning