Contains Duplicate
Easy · Arrays & hashing
Jump to codeDecide whether an integer array contains any repeated value. Return true when two different positions hold the same number.
Examples
Example 1
nums = [1,2,3,1]
Output: true
Example 2
nums = [1,2,3,4]
Output: false
Constraints
- The input is an array of integers. Empty input has no duplicates.
Need a hint?
Only membership matters; the earlier position is irrelevant.
Real array interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Find the Earliest Pair with a Target SumAmazon
- Smallest Missing Positive Integer in Linear Time and Constant Extra SpaceGoogle
- Find Users with at Least One Session Within a Duration LimitLinkedIn
Solution approach
Maintain a set of visited values. If the next number is already in the set, return true. Otherwise insert it and continue. Return false after processing the entire array. An empty array has no duplicate.
Complexity
O(n) expected time and O(n) space.
Python reference solution
def containsDuplicate(nums):
seen = set()
for value in nums:
if value in seen:
return True
seen.add(value)
return False
JavaScript solution
function containsDuplicate(nums) {
const seen = new Set();
for (const value of nums) {
if (seen.has(value)) return true;
seen.add(value);
}
return false;
}
Java solution
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int value : nums) {
if (!seen.add(value)) return true;
}
return false;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int> &nums) {
unordered_set<int> seen;
for (int value : nums) {
if (!seen.insert(value).second) return true;
}
return false;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 11 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
2,
3,
1
]
]true
[
[
1,
2,
3,
4
]
]false
[
[
1,
1,
1,
3,
3,
4,
3,
2,
4,
2
]
]true
[
[
42
]
]false
[
[
-1,
-2,
-3,
-1
]
]true
Drafts are saved per language in this browser when storage is available.