Pattern this teaches:Hashing and Frequency Maps
Contains Duplicate
An easy Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Arrays
- Sheets
- 2
- Core for
- 26 roles
The problem
Given an integer array, determine whether any element appears at least twice in the collection.
Example 1
- Input
- nums = [4,7,1,7]
- Output
- true
- Why
- The value 7 appears at index 1 and again at index 3.
Example 2
- Input
- nums = [9,2,6,5]
- Output
- false
- Why
- All four values are different, so nothing repeats.
Example 3
- Input
- nums = [5,5,8,2,2,9,8,1,5,3]
- Output
- true
- Why
- Several values repeat here, for example 5 appears three times and 8 twice.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
How to think about it
Updated 2026-09-29The question does not care where copies sit or how many times a duplicate repeats; it only asks if the count of unique values is strictly less than the total count. Tracking seen keys in an unordered hash set detects collisions the moment a repeated number is encountered, short-circuiting the remainder of the array.
Approaches, worst first
Nested pair comparison
time O(n^2) · space O(1)
Compare every pair of elements using nested loops to verify if nums[i] == nums[j]. Requires no auxiliary memory, but runs in quadratic time and times out on larger arrays.
Sort and adjacent check
time O(n log n) · space O(1)
Sort the array ascending so duplicate values cluster into adjacent positions. A single linear scan checks whether nums[i] == nums[i - 1]. Avoids dynamic memory allocation at the cost of an O(n log n) sorting step and mutating the input order.
Hash set membership testWrite this one
time O(n) · space O(n)
Traverse elements while adding each to a hash set. If an insertion query indicates the value is already present in the set, terminate early and return true. Returns false if the scan finishes with all unique elements.
Where people lose marks · 3
- Allocating a fixed-size boolean frequency array indexed by values when nums[i] contains negative numbers or ranges up to 10^9.
- Comparing the size of the set only after inserting all elements instead of early-exiting on the first duplicate encounter.
- Assuming a single-element array has duplicates instead of returning false immediately.
Full solution
Hash set membership test: one pass, early-exit on the first repeat. The nested-loop and sort-based approaches both work but are strictly worse here — O(n) time and space beats them without the input-mutation tradeoff sorting requires.
Python
def contains_duplicate(nums: list[int]) -> bool:
seen: set[int] = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
JavaScript
function containsDuplicate(nums) {
const seen = new Set();
for (const num of nums) {
if (seen.has(num)) return true;
seen.add(num);
}
return false;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
More Arrays problems
Target Roles
Core requirement for 26 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .