Back to solutions
Contains Duplicate
EasyArraysDecide whether any value appears at least twice in the array.
Constraints
- 1 <= n <= 10^5
- -10^9 <= nums[i] <= 10^9
Hash set membership
Time O(n)Space O(n)
Keep a set of the values you have already seen. Walk the array once: if the current value is already in the set a duplicate exists, otherwise add it. Set lookups are O(1) on average.
Key terms
- set:
- A collection that stores each value at most once and answers 'is x present?' in average O(1).
- membership test:
- Checking whether a value already belongs to a collection before inserting it.
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
for (int x : nums) {
if (seen.count(x)) return true;
seen.insert(x);
}
return false;
}Step by step
- Create an empty set `seen`.
- Iterate over each value x in the array.
- If x is already in `seen`, a duplicate is found return true.
- Otherwise insert x into `seen` and continue.
- If the loop finishes with no repeat, return false.
- The driver prints the boolean as the lowercase word true or false.