← Back to DSA Animator
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 (seen values)
{ empty }
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.