Stage 1: Foundations·Arrays & Hashing
Easy#2174 min readHashingSetLeetCode

Contains Duplicate

HashSet membership

HashSet existence check. Think about why this is O(n) not O(n²).

Published Apr 15, 2026

Problem

Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.

Input
nums = [1, 2, 3, 1]
Output
true
Input
nums = [1, 2, 3, 4]
Output
false

Intuition

The brute-force instinct is to compare every pair. That works, but it asks the same question over and over: "have I seen this value already?"

That question has a direct data-structure answer: a HashSet.

As you scan left to right, either the current value is new, or it is already present in the set. The moment it is already present, you have found a duplicate and can return immediately.

Approach

HashSet Scan

TimeO(n)
SpaceO(n)
Recommended

Walk the array once. Maintain a set of values seen so far.

  • If x is already in the set, return true.
  • Otherwise insert x and continue.
  • If the scan finishes, every value was distinct.
use std::collections::HashSet;

impl Solution {
    pub fn contains_duplicate(nums: Vec<i32>) -> bool {
        let mut seen = HashSet::with_capacity(nums.len());
        for x in nums {
            if !seen.insert(x) {
                return true;
            }
        }
        false
    }
}
Rust · runnable

Language notes:

  • RustHashSet::insert returns false if the value was already present, which makes the duplicate test one line.
  • TypeScriptSet gives the same membership semantics directly. No need to sort or count.

Edge cases

  • Empty array — no duplicate exists, so return false.
  • Negative values or large values — hashing does not care about numeric range.
  • Duplicate at the front — early return means best-case work can be much smaller than n.

Takeaway

If the real question is "have I seen this before?", the answer is usually a set.

This is the smallest possible HashSet problem, but the reflex matters. The same lookup pattern drives #1 Two Sum, #242 Valid Anagram, and #128 Longest Consecutive Sequence.

More in Arrays & Hashing