2. Contains Duplicate
Return true if any value appears at least twice in nums, and false if every element is distinct.
Example 1
Input:
nums = [3,1,4,1]Output:
trueExample 2
Input:
nums = [7,8,9]Output:
falseConstraints
1 ≤ nums.length ≤ 10⁵
Hint 1
What data structure answers “have I seen this before?” in O(1)?
Approach 1: Sort
Sort the array; duplicates become neighbours.
⏱ Time O(n log n)💾 Space O(1)
Approach 2: Hash set ✅
Insert each value into a set; if it is already there, return true.
⏱ Time O(n)💾 Space O(n)
Reference solution for Hash set (time O(n), space O(n)). Each solution passes every test in all four languages.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return Falseclass Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums)
if (!seen.add(x)) return true; // add() returns false if x was already there
return false;
}
}class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
for (int x : nums)
if (!seen.insert(x).second) return true; // insert fails if x already exists
return false;
}
};function containsDuplicate(nums) {
const seen = new Set();
for (const x of nums) {
if (seen.has(x)) return true;
seen.add(x);
}
return false;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
This problem is explained in the lesson Arrays, Hashing & Prefix Sums.
Run your code to see results here.