Skip to the workspace
Pebellslearn by building
Arrays & Hashing  ›  Lesson

The Seen-Set: Spotting Repeats in One Pass

Contains Duplicate 12 minTo find a repeated item, walk the list once and ask a set whether it has seen each item before adding it, which replaces a comparison of every pair with a single pass.

leetcode / The Seen-Set: Spotting Repeats in One Pass

Explore each scene at your own pace.

01 · The rule

The rule

The Seen-Set: Spotting Repeats in One Pass

A concert gate scans ticket codes as people walk in. If a code has already been scanned, someone has copied a ticket and the gate must flag it. Comparing every ticket with every other ticket would keep the queue waiting for hours. A set remembers what it has seen and answers "was this here before?" in an instant.

The rule

Before you store it, ask the set whether it has seen it.

The slow way compares every pair: for 100,000 tickets that is about five billion comparisons. The seen-set does one question and one insert per item:

def first_repeat(codes):
    seen = set()
    for code in codes:
        if code in seen:       # ask first...
            return code
        seen.add(code)         # ...then store
    return None

first_repeat(["A7", "B2", "C9", "B2"]) returns "B2". The cost is one pass, n steps, plus memory for up to n codes. Memory is the price you pay for speed, and it is almost always worth it.

The same move answers many disguised questions: the first repeated letter in a word, whether two sign-ups share an email, whether a walk on a grid ever returns to a square it has visited.

If you only need yes or no, Python has a one-liner: a set drops duplicates, so the list has a repeat exactly when the set is smaller.

has_repeat = len(set(codes)) != len(codes)

There is a third option when memory is tight: sort, then compare neighbours. Equal items end up side by side, so one pass over the sorted list finds them. That costs n log n time but no extra set, and it is the answer to the follow-up question "what if you cannot afford a big extra set?"

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.