1Question
You are given an array of numbers called nums. Return true if any number appears at least two times. Return false if every number is different.
Two positions with the same value. They do not need to be next to each other.
In [1, 2, 3, 1] the 1 at index 0 and the 1 at index 3 are duplicates.
The number 1 appears at index 0 and at index 3.
All four numbers are different.
Many numbers repeat. We can stop at the first repeat we find.
Constraints
Up to 100,000 numbers. Comparing every pair is about 5 billion checks, which is too slow. We want O(n).
Numbers can be very big or negative, so we can not use them as list positions (no “counting array”). A hash set works for any value.
If memory is tight, sorting first gives O(n log n) time with little extra space.
2Hints
Open one hint at a time. Try to think before you open the next one.
3Pattern
Hash Set Lookup
Trade a little memory for a lot of speed.
A hash set stores values so that checking x in seen takes constant time on average. Instead of looking back through the whole array, we ask the set:
Each number is checked once and added once. That turns an O(n²) search into one O(n) pass.
How to spot this pattern
- The question asks “have I seen this before?”
- You need to find repeats, pairs or missing values.
- Order does not matter, only membership.
- You are allowed O(n) extra memory.
4Explanation
The big idea: Walk through the array one number at a time and keep a set called seen. At every number there are only two cases:
The number is in seen. We found a duplicate. Return True right away.
The number is not in seen. Add it, and move to the next number.
If the loop ends without finding a repeat, every number was different, so return False.
Why is it correct? When we reach a number, seen holds exactly the numbers before it. So “in seen” means “appeared earlier”, which is the definition of a duplicate.
5Brute Force
Compare every pair of numbers.
Idea
A pair is fixed by two positions i and j with i before j. So we:
- Pick every first position
i. - Compare it with every later position
j. - If the two values are equal, return true.
def contains_duplicate_brute(nums):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j]: # same value at two positions
return True
return False
print(contains_duplicate_brute([1, 2, 3, 1])) # True6Optimal Solution
One pass with a hash set.
def contains_duplicate(nums):
seen = set() # numbers we have already visited
for num in nums:
if num in seen: # O(1) on average
return True
seen.add(num)
return False
print(contains_duplicate([1, 2, 3, 1])) # True7Time and Space Complexity
Let n be the number of items in the array.
Brute force
Optimal (hash set)
How big is the difference?
Approximate number of steps:
| n | Brute force (n²/2) | Hash set (n) |
|---|---|---|
| 10 | 45 | 10 |
| 1,000 | 499,500 | 1,000 |
| 100,000 | about 5 billion | 100,000 |
The set uses more memory, but for 100,000 numbers it does around 50,000 times less work.