Approach
Use a hash set with a single pass:
- Create an empty
Set<number>namedseen. - Iterate through each number in
nums. - If the current number already exists in
seen, returntrueimmediately. - Otherwise, add the number to
seenand continue. - If the loop finishes without finding a repeat, return
false.
Why this works:
seenstores every unique number encountered so far.- The first time a value repeats,
seen.has(value)detects it in constant average time.
Implementation
export function containsDuplicate(nums: number[]): boolean {
const seen = new Set<number>();
for (const num of nums) {
if (seen.has(num)) return true;
seen.add(num);
}
return false;
}Complexity
- Time O(n): single pass over
nums, with averageO(1)set lookup/insert per element. - Space O(n): in the worst case (all unique values), the set stores every number once.
Test Coverage
The test suite validates:
- LeetCode baseline examples
- Empty and single-element inputs
- Negative values and zeros
- Duplicates that appear far apart
- Unique unsorted arrays
- Large deterministic inputs (10k values)
- Input non-mutation behavior