Contains Duplicate

easyTests passed 2026-11-11v1.0.0

1. Core Invariant / The Trick

Maintain a hash set of previously seen numbers. Return True immediately if the current element is already in the set; otherwise insert and continue.

2. Complexity Bounds & Proof

Single linear pass inserting at most N distinct elements with O(1) expected set operations.

3. Minimal Idiomatic Code

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

4. Failure Modes & Interview Follow-ups

Pitfalls:- Sorting mutates the input array and takes O(N log N) time; prefer O(N) hash set unless constrained by strict O(1) auxiliary space.
Follow-ups:- Contains Duplicate II (within distance k): maintain a sliding window set of size <= k.

Personal Notes & Scratchpad (Local-First Yjs CRDT)

Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.

Related Invariants

Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.