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.
1function containsDuplicate(nums: number[]): boolean {2▶ const seen = new Set<number>();3 for (const x of nums) {4 if (seen.has(x)) return true; // repeat → done5 seen.add(x);6 }7 return false; // all unique8}
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.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
}The most literal reading: for each element, scan every later element and return true the moment two are equal. No extra data structures.
function containsDuplicate(nums: number[]): boolean {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] === nums[j]) return true;
}
}
return false;
}O(n²) and degrades badly on large arrays. Trading O(n) memory for a Set (the optimal) lets each lookup be O(1), finishing in a single O(n) pass.| "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: