Free beta: 30 days of full access, no card needed.Sign up free

We use necessary cookies to run the site (sign-in and language). The contact and bug-report forms also use Google reCAPTCHA for spam protection, loaded only if you accept. Privacy policy

Field manual

Hash set / map

O(n)

Trade memory for speed: a set answers "have I seen this" in O(1), a map counts "how many of each" in one pass over unsorted data.

Signals

have I seen this beforecount how many of eachfind duplicatesdoes a matching/complement value existdata is in any order / unsorted

Template

function firstDuplicate(arr) {
    const seen = new Set();
    for (const x of arr) {
        if (seen.has(x)) return x;
        seen.add(x);
    }
    return null;
}

Looks similar, isn't

  • Two pointers (opposite ends): Two pointers need a sorted array and give O(1) space. If the data is unsorted and you cannot pay to sort it, a hash structure is the O(n) answer.
  • Sliding window: A window answers a question about a contiguous span. A plain set/map answers membership or frequency over the whole collection, with no notion of a span.

unsorted, n up to 1e5..1e6, one membership/frequency question -> O(n) time, O(n) space. The constraint that rules out sorting is what points here.

Learn this pattern