—
Decide whether any value appears more than once. The naive approach compares all pairs in O(n²); the clean answer streams through once, remembering everything it has seen in a hash set and stopping the instant it meets a repeat.
Return true if any value in nums appears at least twice, else false. For [1,2,3,1] → true (the 1 repeats). For [1,2,3,4] → false.
Setanswers "have I seen this exact value before?" in O(1). Stream through the array; the first time a value is alreadyin the set, you've found a duplicate and can return immediately.You don't need counts or positions — only the binary fact of membership. That's exactly what a set gives you, more cheaply than a map.
true right away.false.new Set(nums).size !== nums.length — is correct but always builds the whole set (no early exit).Sorting trades the set's O(n) space for O(1) (in place) but costs O(n log n) time. If memory is tight, sort; if speed matters and memory is fine, the set wins. State this tradeoff out loud — interviewers love it.
function containsDuplicate(nums: number[]): boolean {
const seen = new Set<number>();
for (const x of nums) {
if (seen.has(x)) return true; // repeat → done
seen.add(x);
}
return false; // all unique
}Set stores only membership — no counts, no indices — which is all this problem needs.true immediately. This early exit is the difference from the always-build-the-whole-set one-liner.false; the loop handles them naturally.| "any element repeated?" | hash Set, early exit |
| only membership matters (not count) | Set over Map |
| "within distance k" | sliding-window Set |
| O(1) space required | sort + adjacent check |
const seen = new Set<number>();
for (const x of nums) {
if (seen.has(x)) return true;
seen.add(x);
}
return false;Set. We only need membership ("seen it?"), not counts or indices.[1,2,3,4] the function returns:[2,2,...] (repeat at the front), the set approach:[] returns: