LeetCode 217
Contains Duplicate
Tell whether any value shows up more than once. A set remembers what you've seen and answers in one pass.
The problem
Given an integer array, return true if any value appears at least twice, and false if every element is distinct.
Comparing every pair is O(n²), and sorting first to spot neighbours is O(n log n). Both do more work than the question needs — all I really have to know is whether I've encountered a value before.
The approach
Keep a set of the values seen so far. For each number, if it's already in the set I've found a duplicate and can stop immediately.
Otherwise add it and continue. The early return means the best case is fast, and if the array is fully distinct I simply fall through to false after one pass.
The solution
function containsDuplicate(nums: number[]): boolean {
const seen = new Set<number>();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}Time O(n)Space O(n)