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

Edge cases to test

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 False

C++

#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