Contains Duplicate problem in Python – Check Duplicates Easily

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.

Constraints:

Examples:

Input:[1,2,3,1]

Output: true

Explanation: The array contains duplicate elements (1 appears twice).

Input:[1,2,3,4]

Output: false

Explanation: The array does not contain any duplicate elements.

Input:[1,1,1,3,3,4,3,2,4,2]

Output: true

Explanation: The array contains duplicate elements (1, 3, and 2 appear multiple times).

Solutions

We use a hash set to store unique elements from the array. We iterate through the array, and for each element, we check if it already exists in the set. If it does, we return true, indicating that the array contains duplicates. If we finish iterating through the array without finding any duplicates, we return false.


def containsDuplicate(nums):
    set_ = set(); for num in nums:
        if num in set_:
            return True; set_.add(num); return False

Follow-up:

How would you solve this problem if the array is too large to fit into memory?