DSA Visualizer · 25 visualizationsContains Duplicate
EasyArrays & Hashing
Contains Duplicate
Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
nums = [1, 2, 3, 1]Step 1 of 5
1
02
13
21
3seen (set)
emptyStart with an empty set. It will remember every value we have already walked past.
Pythontime O(n) · space O(n)
1def containsDuplicate(nums):
2 seen = set()
3 for n in nums:
4 if n in seen:
5 return True
6 seen.add(n)
7 return False
Variables
i—
n—
seen{}
Problem
Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
Examples
Input: nums = [1,2,3,1]Output: true
1 appears at index 0 and 3
Input: nums = [1,2,3,4]Output: false
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
Intuition
A repeat means the array holds fewer distinct values than it has slots. We can compare every pair, or remember each value as we walk the array once.
Brute force → Optimal
Brute force
Compare every pair (i, j) with i < j and return true as soon as two values are equal.
Time O(n²)Space O(1)
Optimal
Insert each number into a hash set while scanning left to right. If the number is already in the set, a duplicate exists.
Time O(n)Space O(n)
Complexity
Time O(n)Space O(n)
Edge cases
- Two equal values next to each other, e.g. [7, 7], are caught on the second step.
- All distinct values, e.g. [1, 2, 3, 4], make the scan finish and return false.
Common mistakes
- Adding the number to the set before checking, which hides the duplicate.
- Returning the duplicated value instead of a boolean.
Invert Binary TreePrevious
Next upGroup Anagrams
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free