217. Contains Duplicate
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Arrays & Hashing
- Time
- O(N)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven an integer array, determine whether any value appears more than once — return true if a duplicate exists, false if every element is unique.
Approach
- Insert each element into a hash set as we iterate through the array.
- Before inserting, check whether the element already exists in the set; if so, a duplicate has been found.
- Because hash set lookups and insertions are O(1) average, a single linear pass is sufficient.
- If we exhaust the array without a hit, all values are distinct and we return false.
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
seen.reserve(nums.size()); // avoid rehashing for large inputs
for (int n : nums) {
// Try to insert; if already present, emplace returns false
if (!seen.emplace(n).second) {
return true;
}
}
return false;
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> uset;
for(const int n: nums){
if(uset.count(n)){
return true;
}
uset.insert(n);
}
return false;
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) Time O(N) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.