Contains Duplicate

EasyHashing · Hash Set🧩 Hashing & CountingLeetCode #217 ↗Updated

Problem

You get an integer array nums. Return true if some value occurs two or more times anywhere in it, and false when every element is unique.
Input[4,7,1,7]Outputtrue
Input[5,6,8,9]Outputfalse
Input[2,2,2,3,3]Outputtrue

1 ≤ n ≤ 105  ·  -109 ≤ nums[i] ≤ 109

Try it yourself

Java
class Solution {
    public boolean containsDuplicate(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
You only need to answer “have I seen this value before?” for each element — a hash set answers that in O(1), and the first repeat ends the scan.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceCompare Every Pair

Time O(n2)Space O(1)

A duplicate is just a pair i < j with equal values. Two nested loops try every such pair and stop at the first match; if none matches, all values are distinct.

Java
public boolean containsDuplicate(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] == nums[j]) return true;
        }
    }
    return false;
}

Zero extra memory, but ~5·109 comparisons at n = 105 — too slow.

At a glance

LevelApproachTimeSpace
Brute ForceCompare Every PairO(n2)O(1)
BetterSort, then Check NeighboursO(n log n)O(n) copy (O(log n) in place)
OptimalHash Set of Seen ValuesO(n)O(n)
Common pitfalls
  • Starting the inner loop at j = 0 — compares an element with itself.
  • Sorting the caller's array without saying so — a hidden side effect.
  • Building the whole set first and comparing sizes — correct, but loses the early exit.
Interview tips
  • Ask whether the input may be modified — it decides between in-place sort and a copy.
  • Name the time–space trade-off: sort uses little memory, the set is linear time.
  • Mention that add() returning false doubles as the lookup.
Pattern
Hash set membership → “have I seen this before?” questions over a single pass.
My notes saved in this browser