lc.algoro.dev
← Back to problems

Contains Duplicate

Easy #217 View Problem ↗ Array • Hash Table • Sorting

Intuition

We need to check whether any number appears more than once.

A brute force nested-loop comparison would be too slow (O(n²)). Instead, we can exploit the fact that sets only store unique elements. If we ever encounter a number we’ve seen before, we found a duplicate.


Approach

  1. Initialize an empty set.
  2. Traverse the array:
  1. If traversal finishes with no duplicates → return False.

Proof of Correctness

At each step, the set contains all unique elements seen so far. If a duplicate exists, the second occurrence will be found during traversal because x ∈ set check will succeed. If no duplicate exists, traversal ends with no True. Thus, correctness is guaranteed.


Complexity


Code

TypeScript Solution
export function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();

  for (const num of nums) {
    if (seen.has(num)) {
      return true;
    }
    seen.add(num);
  }

  return false;
}
Python Solution
def containsDuplicate(self, nums):
        seen = set()
        for num in nums:
            if num in seen:
                return True
            seen.add(num)
        return False