Typorithm · easy

Contains Duplicate

contains-duplicatearrays-hashinghash-setmembershipearly-exit
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Contains Duplicate

0%

Arrays & Hashing

Track seen values in a Set; the first repeat returns true, otherwise return false.

A Set membership test is O(1), so scanning once is enough.

Each value is checked, then added; a hit on the check means a duplicate.

The early exit stops as soon as the first repeat is found.

01

Set membership is O(1).

02

Check, then add.

03

Early-exit on the first repeat.

function containsDuplicate(nums) {
  const seen = new Set();

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

    seen.add(num);
  }

  return false;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Seen set

A Set gives O(1) membership tests with no duplicate keys.

const seen = new Set()

2. Already seen?

If the value is already present, a duplicate exists.

if (seen.has(num))

3. Remember it

Record the value so later repeats are caught.

seen.add(num)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Contains Duplicate: Lesson & Practice · Typorithm | ApplyDjinn