Approach 1Optimal▶ Animated
One-pass hash set
Remember every value. A hit means a duplicate.
A set answers “have I seen this?” in expected O(1). Insert after the lookup so a value never pairs with itself.
Algorithm
- Empty set
seen. - For each
x, ifxis inseenreturn true; otherwise insert it. - If the walk finishes, return false.
- Time
- O(n)
- Space
- O(n)
class Solution: def containsDuplicate(self, nums: list[int]) -> bool: seen: set[int] = set() for x in nums: if x in seen: return True seen.add(x) return False