DSA AnimatorDSA animations
Contains DuplicateLC #217EasyHashing
Problem

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

Example 1
Input: nums = [1,2,3,1]
Output: true
Example 2
Input: nums = [1,2,3,4]
Output: false
Constraints: 1≤nums.length≤10⁵  |  −10⁹≤nums[i]≤10⁹
Try Examples
Custom:
Approach
HashSet — O(1) Lookup per Element
For each element: check if it's already in the set. If yes → duplicate found, return true. If no → add it. If we finish the loop without a hit → return false.
Array
HashSet (The Magic Bucket)
✨ It's completely empty... for now! ✨
Variables
Index i
—
nums[i]
—
set size
0
result
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Create empty HashSet
2
For each nums[i]: check if it's in the set
3
If set contains nums[i] → return true (duplicate!)
4
Otherwise add nums[i] to set and continue
Time
O(n)
Space
O(n)
Why It Works

HashSet lookup and insert are both O(1) average. We only need to know if a value was seen before — not its index or count. The moment we encounter a value already in the set, we know there's a duplicate.

How to solve Contains Duplicate

LeetCode 217 · Easy · Arrays · Pattern: Hash Set

Why the obvious approach is slow

Comparing every pair is O(n²). Sorting and checking neighbours works too, but costs O(n log n).

The key idea

Keep a hash set of the values seen so far. If the current value is already in the set, you found a duplicate.

Remember

Seen before means a hash set lookup. Stop as soon as the first duplicate appears.

Run the animation above on your own input, or watch the 0:55 video explanation of Contains Duplicate with a dry run and Java code.

More Arrays problems