Fade to Solo
Arrays & Hashing

Contains Duplicate

STUDYEleetcode ↗

Problem

Given an array of integers, determine whether any value appears at least twice.

Signal

"Seen it before?" over an unsorted collection, where order doesn't matter, is a hash-set membership check — O(1) lookups beat sorting or nested loops.

Approach

Walk the array once, adding each value to a set. If a value is already in the set when you go to add it, you've found a duplicate — return immediately.

Skeleton

seen = {}
for x in nums:
    if x in seen: return True
    seen.add(x)
return False

Solution

def contains_duplicate(nums: list[int]) -> bool:
    seen: set[int] = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False

Complexity

O(n) time — one pass with O(1) set operations. O(n) space for the set in the worst case (no duplicates found).

Pitfalls

  • Sort-then-compare-adjacent also works, but it's O(n log n) — the hash set wins whenever the extra O(n) space is acceptable, which it almost always is.
  • len(nums) != len(set(nums)) is a tidy one-liner, but it builds the whole set up front instead of short-circuiting on the first duplicate.
  • Empty and single-element inputs return False for free if the loop is written correctly — no special-casing needed.