Coding interview problems › Arrays & Hashing
#️⃣ Arrays & Hashing Easy
Contains Duplicate
Contains Duplicate explained: use a hash set to spot a repeated value in one O(n) pass, plus the sorting alternative, tested Python and a live visual.
Also searched as: check if array has duplicates · find duplicate elements in array python
Try it live Free
Hash Tables
Insert keys into the hash table and watch where each lands. When a key you insert is already sitting in its bucket, that is the duplicate this problem is looking for.
The problem
Given a list of integers nums, return True if any value appears at least twice, and False if every value is distinct.
1 appears twice.
The key insight
A duplicate means "I have seen this value before". A hash set remembers everything seen so far and answers membership in O(1), so the first time a value is already in the set you can stop.
Step-by-step approach
- Create an empty set
seen. - For each value
x: ifxis inseen, returnTrueimmediately. - Otherwise add
xtoseen. - If the loop finishes, every value was new, so return
False.
Python solution
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return FalseComplexity
One pass with average O(1) set lookups. The set can grow to hold every element when there is no duplicate.
Common mistakes
- Writing a nested loop that compares
nums[i]withnums[j]for all pairs, which times out on large inputs. - Using a list instead of a set for
seen;x in listis O(n), so the whole thing becomes O(n²) again. - Sorting the input in place when the caller still needs the original order.
Frequently asked questions
What is the time and space complexity of Contains Duplicate?
The hash set solution runs in O(n) time with O(n) extra space. Sorting and checking neighbours is O(n log n) time with O(1) extra space if you may modify the input.
Is len(set(nums)) != len(nums) acceptable?
Yes, it is a correct one-liner with the same O(n) complexity. It cannot stop early, so the explicit loop is slightly faster when a duplicate appears near the start.
What if duplicates only count within distance k?
That variant keeps a sliding window of the last k values in a set, adding the new value and removing the one that falls out of the window.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Arrays & Hashing Hash Tables lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.