The problem, in one line. Given a list of numbers, say whether any value appears more than once. LeetCode 217.
The tell. The question is only “has this value shown up before?” and nothing needs to stay sorted. Any time you ask whether you have seen something already, the tool is a set.
The wrong first idea
Compare every number with every number after it.
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return False
Correct, and fine for ten numbers. It checks every pair, so 100,000 numbers means about 5 billion comparisons. Doubling the list quadruples the work, which is the sign that a second walk is hiding inside the first.
The invariant
Walk the list once and keep a set of the values already passed. Standing on x, the question “did I pass this before?” is one lookup, not another walk.
flowchart LR
A["x = 1<br/>seen: {}"] --> B["x = 2<br/>seen: {1}"]
B --> C["x = 3<br/>seen: {1, 2}"]
C --> D["x = 1<br/>seen: {1, 2, 3}"]
D -->|"1 is already in seen"| E["answer: True"]
The sentence that stays true every step: the set holds exactly the values to my left. The first time the current value is already in it, the answer is yes, and you can stop without reading the rest.
The solution
def contains_duplicate(nums):
seen = set() # every value already passed
for x in nums:
if x in seen: # it went past before
return True
seen.add(x)
return False
print(contains_duplicate([1, 2, 3, 1]))
print(contains_duplicate([1, 2, 3, 4]))
print(contains_duplicate([]))
True
False
False
func containsDuplicate(nums []int) bool {
seen := map[int]struct{}{} // every value already passed
for _, x := range nums {
if _, ok := seen[x]; ok { // it went past before
return true
}
seen[x] = struct{}{}
}
return false
}
Same three calls print true, false, false.
Complexity
- Time O(n): one pass, one lookup and one insert per number.
- Space O(n): when there is no duplicate the set ends up holding every number.
Traps
- Adding to the set before checking it. Every value then “finds itself” and
[1, 2, 3, 4]wrongly returnsTrue. - Checking only neighbours.
[1, 2, 1]has a duplicate that is not next to its twin. - Reaching for
len(set(nums)) != len(nums)and calling it a trick. It is correct, but it always reads the whole list, so a repeat in the first two slots of a million numbers still costs a million steps.
Next in the ladder
Valid Anagram keeps the same “remember what went past” idea but asks how many times, so a set of values becomes a map of counts.