Algo-Sim › Arrays & Hashing
Contains Duplicate
Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Does any value appear at least twice? One pass with a hash set.
Problem
You are given an integer array nums. Return true if at least one value occurs two or more times, and false if every value is different.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
- n up to 10⁵ rules out comparing every pair (O(n²))
Edge cases to test
- Empty array or a single element:
false - The duplicate is the last pair:
[1, 2, 3, 1] - Negative values and
0hash like any other
Follow-up questions
- What if you need O(1) extra space?
- Sort in place and compare neighbours: O(n log n) time, O(1) extra space (O(log n) for the sort’s stack).
- What if duplicates only count within k positions of each other?
- Keep a sliding-window hash set of the last k values (LC 219): O(n) time, O(k) space.
- What if the data is too big for memory?
- Partition by hash into files that each fit, then check each file with a set: one extra read and write pass. A Bloom filter gives a fast "maybe seen" with false positives.
Solution
Java
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums) {
if (seen.contains(x)) {
return true;
}
seen.add(x);
}
return false;
}Python
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return FalseC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int> &nums) {
unordered_set<int> seen = {};
for (int x : nums) {
if (seen.count(x)) {
return true;
}
seen.insert(x);
}
return false;
}
};
More Arrays & Hashing problems
- Valid Anagram (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)