Contains Duplicate (LeetCode 217): Solution and Explanation
Given an array of integers, return true if any value appears at least twice, and false if every element is distinct.
Watch it run step by step
Try your own input and write the code →Intuition
The most direct reading of the problem is to compare every element with every other element and report a match. That brute force is O(n²), and with up to 100,000 numbers it means billions of comparisons. The real question each element asks is narrower: has this exact value appeared anywhere before me? You do not care where or how many times, only whether.
A hash set is built for that question. It stores values without order and answers membership in constant average time. So you can walk the array once, and for each number first ask the set whether it is already there. If it is, you have found a duplicate and can stop immediately. If not, add it and keep going. By the time you look at element i, the set holds every distinct value from indices 0 through i - 1, so a duplicate can never slip by.
Another observation leads to a different solution: if you sort the array, equal values end up next to each other, so one pass comparing neighbors finds any duplicate. That trades the extra memory of the set for O(n log n) time. The hash set wins on time, and it also exits early as soon as it sees the first repeat, which on inputs with an early duplicate means it barely does any work at all.
It is worth noticing what the constraints say. Values range across roughly two billion possibilities, so you cannot use a simple boolean array indexed by value the way you might for small integers. A hash set handles that sparse range gracefully, because it only spends memory on values that actually occur.
Approach: Hash set with early exit
- Create an empty set called
hashset. - Iterate through each number
ninnums. - If
nis already inhashset, returnTruebecause this value has been seen before. - Otherwise add
ntohashsetand continue. - If the loop finishes without finding a repeat, return
False.
Step-by-step example
nums = [1, 2, 3, 1]
- n = 1: the set is empty, so add 1. Set = {1}.
- n = 2: not in the set, add it. Set = {1, 2}.
- n = 3: not in the set, add it. Set = {1, 2, 3}.
- n = 1: 1 is already in the set, so return True without looking further.
Code: Python, Java, C++
1class Solution:
2 def containsDuplicate(self, nums: List[int]) -> bool:
3 hashset = set()
4 for n in nums:
5 if n in hashset:
6 return True
7 hashset.add(n)
8 return False1class Solution {
2 public boolean containsDuplicate(int[] nums) {
3 Set<Integer> set = new HashSet<>();
4 for (int x : nums) {
5 if (set.contains(x)) {
6 return true;
7 }
8 set.add(x);
9 }
10 return false;
11 }
12}1class Solution {
2public:
3 bool containsDuplicate(vector<int>& nums) {
4 unordered_set<int> s;
5 for (int x : nums) {
6 if (s.count(x)) return true;
7 s.insert(x);
8 }
9 return false;
10 }
11};Time and space complexity
O(n)
Each element triggers one membership check and at most one insertion, and both are O(1) on average for a hash set. In the worst case (all distinct) we scan all n elements once.
O(n)
If every value is distinct, all n of them are stored in the set before the function returns false.
Other approaches
Sort and compare neighbors (time O(n log n), space O(1) to O(n))
Sort the array, then check whether nums[i] == nums[i - 1] for any i. It uses no hash set, which helps when memory is tight, but it modifies the input and sorting costs O(n log n). Space depends on the sort implementation.
Compare set size to array length (time O(n), space O(n))
Return len(set(nums)) != len(nums). It is a one-liner with the same O(n) complexity, but it always processes the entire array, so it cannot stop early on the first duplicate.
Common mistakes
- Adding the number to the set before checking membership. The check then always succeeds and the function returns true on the very first element.
- Using a list instead of a set for the seen values. Membership on a list is O(n), so the whole algorithm silently becomes O(n²).
- Sorting the input in place when the caller still needs the original order. If you use the sorting approach, sort a copy or confirm mutation is allowed.
- Returning false as soon as one element is unique. The answer is false only after every element has been checked.
Frequently asked questions
What is the fastest way to check for duplicates in an array?
A hash set gives O(n) average time: scan once and stop at the first value already in the set. Sorting is O(n log n) and brute force is O(n²).
Can Contains Duplicate be solved in O(1) space?
You can sort in place and compare neighbors, which needs little or no extra memory depending on the sort, but the time rises to O(n log n). With arbitrary integers, O(n) time and O(1) space together is not achievable in general.
Is the set size trick as good as the loop?
It has the same complexity and is shorter, but it always builds the full set. The loop can return after the first duplicate, which is noticeably faster when duplicates appear early.
How is this different from Contains Duplicate II?
The second version only counts duplicates whose indices are at most k apart. That needs a sliding window set or a map of last seen indices instead of a plain set of everything.