Contains Duplicate
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an array of integers nums, return true if any value appears at least twice, and false if every value is different.
Understand the problem
- An array is a list of values, like
[1, 2, 3, 1]. - A duplicate is a value that shows up more than once.
- You don't need to say which value repeats or how many times. One repeat anywhere is enough to answer
true.
Example 1
Input: nums = [1, 2, 3, 1]
Output: trueThe value 1 appears at the start and again at the end.
Example 2
Input: nums = [1, 2, 3, 4]
Output: falseEvery value appears exactly once, so there is no duplicate.
Example 3
Input: nums = []
Output: falseAn empty list has nothing in it, so nothing can repeat.
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk through the numbers one by one and keep a "seen" collection. If the current number is already in it, you found a duplicate.
The naive approach (and why it's slow)
The first idea most people have is to compare every number with every other number:
[1, 2, 3, 1]
1 vs 2 1 vs 3 1 vs 1 ← match!This works, but a list of n numbers has about n × n / 2 pairs. For 100,000 numbers that's about 5 billion comparisons, which is far too slow. This kind of cost is called O(n²) ("n squared"): double the input and the work grows four times.
The key insight
We don't actually care about pairs. For each number we only need to answer one question: "have I seen you before?"
A hash set answers exactly that question in a single step, no matter how many values it holds. (New to hash sets? Read the beginner guide linked at the top of the problem.)
Step by step
Let's run it on nums = [1, 2, 3, 1]:
| Step | Current number | Already in seen? | What we do | seen afterwards |
|---|---|---|---|---|
| 1 | 1 | No | add it | {1} |
| 2 | 2 | No | add it | {1, 2} |
| 3 | 3 | No | add it | {1, 2, 3} |
| 4 | 1 | Yes | return true ✅ |
If we reach the end of the list and never got a "Yes", every number was unique, so we return false.
The code
The reference solution is below in every language, with a comment on each important line. Read it top to bottom and match each line to a row in the table above.
How fast is it?
- Time: O(n). We look at each number once, and each set check takes one step.
- Memory: O(n). In the worst case (no duplicates at all), the set ends up holding every number.
We spend some extra memory to save a huge amount of time. That trade is the main idea of this whole category.
Common mistakes
- Adding before checking. If you add the number to the set and then ask whether it's there, the answer is always "yes" and you return
truefor every input. - Using an array as the "seen" collection.
seen.includes(x)looks just as simple, but it scans the whole array each time, so you're back to O(n²).
Going deeper
- Sort first: after sorting, equal values sit next to each other, so one pass comparing neighbours is enough. That's O(n log n) time but only O(1) extra memory if you may sort in place, a good trade-off to mention when memory is tight.
- The one-liner:
new Set(nums).size !== nums.length(orlen(set(nums)) != len(nums)in Python) is correct, but always builds the whole set, even when the duplicate is in the first two positions.
Reference solution
/**
* @param {number[]} nums
* @return {boolean}
*/
export default function containsDuplicate(nums) {
// Every value we've looked at so far. A Set answers "is x in here?" in one step.
const seen = new Set()
for (const num of nums) {
// Check BEFORE adding: otherwise every number would "find itself".
if (seen.has(num)) return true
seen.add(num)
}
// We checked every number and none repeated.
return false
}export default function containsDuplicate(nums: number[]): boolean {
// Every value we've looked at so far. A Set answers "is x in here?" in one step.
const seen = new Set<number>()
for (const num of nums) {
// Check BEFORE adding: otherwise every number would "find itself".
if (seen.has(num)) return true
seen.add(num)
}
// We checked every number and none repeated.
return false
}def contains_duplicate(nums: list[int]) -> bool:
# Every value we've looked at so far. A set answers "is x in here?" in one step.
seen = set()
for num in nums:
# Check BEFORE adding: otherwise every number would "find itself".
if num in seen:
return True
seen.add(num)
# We checked every number and none repeated.
return False