Contains Duplicate

easyArrays & Hashing11 stepsJava · Python · C++

Return true if any value appears at least twice. Add each value to a hash set; add returns false the moment a value is already there.

▶ Watch the animated trace

Traced input: nums = [1, 2, 3, 1] → true. Original problem: neetcode.io/problems/duplicate-integer

Complexity

BestO(1)
AverageO(n)
WorstO(n)
SpaceO(n)

Best case is a duplicate in the first two elements. The set can hold all n values.

Key idea

Common mistakes

Solution

Java
boolean containsDuplicate(int[] nums) {
    Set<Integer> seen = new HashSet<>();
    for (int i = 0; i < nums.length; i++) {
        if (!seen.add(nums[i])) {
            return true;
        }
    }
    return false;
}
Python
def containsDuplicate(nums: List[int]) -> bool:
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False
C++
bool containsDuplicate(vector<int>& nums) {
    unordered_set<int> seen;
    for (int x : nums) {
        if (!seen.insert(x).second) {
            return true;
        }
    }
    return false;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
All distinct
The scan finishes without a collision.
nums = [1, 2, 3, 4]false
Single element
One value can't repeat.
nums = [7]false
Duplicate right away
Found at index 1, the rest is never read.
nums = [5, 5, 1]true
Negatives and zero
Hashing works the same for negative values.
nums = [0, -1, -1]true
← Valid AnagramMajority Element →