Prompt
Return true if an array has any duplicate elements, false otherwise.
Solution
The Set-size comparison again (see the isogram), applied to arrays: a Set collapses duplicates on construction, so if its size differs from the array's length, something repeated. One line, O(n) time, O(n) space.
The naive alternatives are the reason this gets asked:
arr.some((x, i) => arr.indexOf(x) !== i)— reads clever, is O(n²):indexOfrescans from the start for every element. The classic hidden-quadratic.- Sort then scan neighbors — O(n log n), O(1) extra space if you may mutate. This is the right call when memory is the constraint; trade-offs, not absolutes.
- Incremental Set with early exit: insert one element at a time, return true the moment
hashits. Same O(n) worst case, but stops at the first duplicate — better when duplicates are common and arrays are huge. The one-liner always processes the whole array.
Semantics worth one sentence in the interview: Sets use SameValueZero equality. That means 1 and '1' are different (no coercion — strictness you want), NaN equals NaN (unlike ===), and objects compare by reference — two structurally identical object literals are not duplicates. For "deep duplicates" you'd canonicalize each element (e.g. stable stringify) first.
Red flag: indexOf inside some/filter — O(n²) in one innocent-looking line. If you write the one-liner, be ready to give the early-exit version when asked "what if the array has ten million elements and a dupe at index 2?"
Say it: "Set deduplicates on construction, so size versus length answers it in O(n) — with SameValueZero semantics, so no type coercion and objects compare by reference."