Contains Duplicate
Easy
Topics
Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
Example 1
The shaded cells hold the same value at two indices, so the answer is
true.Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,2,3,1] Output: true
Example 2
Every value appears once, so the answer is
false.Input: nums = [1,2,3,4] Output: false
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
A value is a duplicate the moment we see it a second time. A hash set gives O(1) membership tests, so we can detect a repeat as soon as it occurs instead of comparing all pairs.
Approach
- Create an empty set.
- For each number, if it is already present, return
Trueimmediately. - Otherwise insert it. If the loop finishes, all values were distinct → return
False.
Walkthrough
nums = [1, 2, 3, 1]
1 -> add {1}
2 -> add {1,2}
3 -> add {1,2,3}
1 -> already in set -> return TrueComplexity
- Time — O(n): single pass with O(1) average set operations.
- Space — O(n): the set may grow to hold every element.
Common Pitfalls
- Sorting first (O(n log n)) also works and uses O(1) extra space — a good trade-off to mention if asked to avoid the hash set.
Full Solution — all languages
class Solution:
def containsDuplicate(self, nums):
seen = set()
for v in nums:
if v in seen:
return True
seen.add(v)
return Falseimport java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int v : nums) {
if (!seen.add(v)) return true;
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
for (int v : nums) {
if (seen.count(v)) return true;
seen.insert(v);
}
return false;
}
};/**
* @param {number[]} nums
* @return {boolean}
*/ var containsDuplicate = function(nums) {
const seen = new Set();
for (const v of nums) {
if (seen.has(v)) return true;
seen.add(v);
}
return false;
};