Contains Duplicate
Easy · Arrays & Hashing · Explanation and code example
Hash Set Length
How it works
This approach uses the same idea as the previous hash set method: a set only stores unique values, so duplicates are automatically removed.
Instead of checking each element manually, we simply compare the length of the set to the length of the original array.
If duplicates exist, the set will contain fewer elements.
The logic is identical to the earlier approach — this version is just a shorter and more concise implementation of it.
Steps
- Convert the array into a hash set, which removes duplicates.
- Compare the size of the set with the size of the original array.
- If the set is smaller, return
truebecause duplicates must have been removed. - Otherwise, return
false.
Complexity
- Time complexity:
O(n) - Space complexity:
O(n)
Things to watch for
Using Wrong Comparison in Brute Force
When using nested loops, a common mistake is comparing an element with itself by starting the inner loop at i instead of i + 1.
Modifying Input Array Unexpectedly
The sorting approach modifies the original array, which may not be acceptable in some contexts. If the original order matters, make a copy first.
Python code example
from typing import List
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) < len(nums)
C++ code example
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return unordered_set<int>(nums.begin(), nums.end()).size() < nums.size();
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.