← Problem setPython
#217EasyArrays & hashing
Contains Duplicate
The tell: Asks only whether any value repeats — no positions, no counts.
How you get there
- 1A set answers 'have I seen this?' in constant time.
- 2Comparing len(set(nums)) to len(nums) is the same idea in one line.
- 3Early return on the first repeat avoids building the whole set when a duplicate is near the front.
Solution
def contains_duplicate(nums: list[int]) -> bool:
seen: set[int] = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False- Time
- O(n)
- Space
- O(n)
What goes wrong
Using a list instead of a set for `seen` makes membership O(n) and the whole thing quadratic.