Contains Duplicate
HashSet membership
HashSet existence check. Think about why this is O(n) not O(n²).
Problem
Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
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
O(n)O(n)Walk the array once. Maintain a set of values seen so far.
- If
xis already in the set, returntrue. - Otherwise insert
xand 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
}
}
function containsDuplicate(nums: number[]): boolean {
const seen = new Set<number>();
for (const x of nums) {
if (seen.has(x)) return true;
seen.add(x);
}
return false;
}
Language notes:
- Rust —
HashSet::insertreturnsfalseif the value was already present, which makes the duplicate test one line. - TypeScript —
Setgives 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
HashMap lookup. The most fundamental pattern: trade space for time.
Frequency counting with a fixed-size array or HashMap.
The leap: using a sorted string as a HashMap KEY. Creative key design is a core skill.
Only start counting from sequence beginnings. Think before you loop.