Contains Duplicate
Tell whether any value appears twice in an array, stopping at the first repeat with a hash set.
The problem
You get an integer array nums. Return true if some value appears in it at least twice, and false if every value is different.
Input nums = [4, 11, 7, 11, 2]
Output true
11 appears at index 1 and again at index 3.
Input nums = [6, -1, 9, 0]
Output false
All four values are different.
Key constraint: The array can hold up to 100,000 numbers, so comparing every pair (about 5 billion checks) is far too slow.
How to spot the pattern
- The question is only whether some value repeats, not where or how often.
- Each new number needs just one question answered: did it show up earlier?
The idea
Walk through the array once and keep every value you have passed in a hash set. Before adding a number, ask the set whether it is already there; a yes means you found a repeat and can stop. A set answers that question in O(1) on average, so the whole check takes one pass.
Brute force: Compare every pair of positions with two nested loops, which takes O(n^2) time.
Step by step
- 1Create an empty hash set called
seen. - 2Walk through the array one number at a time.
- 3If the number is already in
seen, returntrue. - 4Otherwise add it to
seenand move on. - 5If the loop finishes, every number was new, so return
false.
See the pattern move
The hashing pattern on a small example. Step through it, or press play.
Code
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return FalseComplexity
Time
O(n)
Space
O(n)
Each number costs one set lookup and at most one insert; when all values are different, the set ends up holding all n of them.
Watch out for
- Keeping the seen values in a list instead of a set, so every lookup scans the list and the whole check becomes O(n^2).
- Using a boolean array indexed by value: the numbers can be negative or as large as 10^9, so there is no small range to index.
Follow-up questions
What if you must use O(1) extra space?
Sort the array in place and compare each number with the next one, since a repeat must sit right next to its twin. That costs O(n log n) time and reorders the input, so mention both trade-offs.
What if the two equal values must be at most k positions apart?
Keep only the last k values in the set: check the new number, add it, and remove the number that falls out of range. That is Contains Duplicate II, still O(n).
In Hinglish
Har number ko set mein daalne se pehle poocho: kya yeh pehle aa chuka hai? Haan, toh duplicate mil gaya, wahin ruk jao.