15% off all plans & roadmaps Use code
See plansContains Duplicate
Updated
TL;DR: Return true if any value in the array appears at least twice. Scan once and keep a hash set of values you have already seen, so each check costs O(1) on average.
Problem
Given an integer array nums, decide whether any value occurs at least twice. The two occurrences can be at any positions.
Return true if some value is repeated. Return false if every value appears exactly once.
Example 1
Input: nums = [8,3,5,8] Output: true Explanation: The value 8 appears at two positions, so the array contains a duplicate.
Example 2
Input: nums = [-4,12,0,7] Output: false Explanation: All four values are different, so there is no duplicate.
Example 3
Input: nums = [6,6] Output: true Explanation: Both elements have the same value, which is enough to return true.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9numscontains only integers.
Constraints that matter
nums.lengthup to 10^5 rules out comparing every pair. That is about 5 * 10^9 comparisons, too slow for a typical time limit.- Values range over -10^9 to 10^9, which is 2 * 10^9 + 1 possibilities. A boolean array indexed by value would need billions of slots, so you need a hash set or sorting.
nums.lengthis at least 1, so you never handle an empty array. A single element always returns false.- Values fit in a 32-bit signed integer, so there is no overflow risk when you only compare for equality. Do not subtract values in a comparator in languages with 32-bit ints.
- Memory for 10^5 integers is small, so spending O(n) extra space on a set is acceptable.
Hints
Hint 1
This is a previously seen check, a form of hashing.
Hint 2
Compare every element with every element after it.
Solution
Intuition
This is a previously seen check, a form of hashing. The question is never about positions or counts. It asks only whether the current value has appeared before. Any time a problem asks "have I met this already?", reach for a hash set.
Picture a bouncer at a club with a guest list that he fills as people walk in. Each new guest is checked against the list, and the list is exactly the set of people already inside. A repeat name at the door means the same person is trying to enter twice.
The pattern shows in how the answer is built. For each element, the only fact you need about the past is membership: is this value among the earlier ones? A hash set answers membership in O(1) on average, so you can process the array in one pass.
Why it works: keep the invariant that before reading nums[i], the set holds exactly the values of nums[0..i-1]. If nums[i] is in the set, an earlier element equals it, so a duplicate exists. If it is not, you add it and the invariant holds for the next step. If the loop ends, no element ever matched an earlier one, so all values are distinct.
Sorting is the other natural route. Equal values end up next to each other after a sort, so one scan of neighbours finds any duplicate. It costs O(n log n) but needs no hashing. Know both, because the interviewer may ask for the one that fits a memory limit.
Worked example
Input: nums = [-1000000000, 1000000000] Output: false Explanation: The array has two elements, -1000000000 and 1000000000. They differ, so no value repeats and the answer is false. The values sit at the extreme ends of the allowed range, which shows that the sign and size of a value do not matter, only equality.
Approach 1: Brute force
Compare every element with every element after it. If any pair is equal, a duplicate exists. This translates the problem statement directly, and it needs no extra memory.
Steps
- Loop
ifrom 0 to n - 1. - For each
i, loopjfromi + 1to n - 1. - If
nums[i] == nums[j], return true. - If both loops finish, return false.
Dry run
On [-1000000000, 1000000000], n is 2.
i = 0:jruns from 1 to 1. Compare-1000000000with1000000000. They differ.i = 1:jstarts at 2, which is past the end, so the inner loop does nothing.- Both loops end without a match, so return
false.
Only one comparison happened. On a large array with all distinct values, you would make about n * (n - 1) / 2 comparisons.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Here n is the array length. The inner loop runs n - 1 times for i = 0, n - 2 times for i = 1, and so on. That sums to n * (n - 1) / 2 comparisons in the worst case (all values distinct), which is O(n^2). The code stores only the two indices, so extra space is O(1). With n = 10^5 the worst case is about 5 * 10^9 comparisons, which is too slow.
PythonTested in our runner
from typing import List, Optional
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
# same value at two different positions
if nums[i] == nums[j]:
return True
return False
JavaTested in our runner
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// same value at two different positions
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}
C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// same value at two different positions
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
const n = nums.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// same value at two different positions
if (nums[i] === nums[j]) {
return true;
}
}
}
return false;
};
GoTested in our runner
func containsDuplicate(nums []int) bool {
n := len(nums)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
// same value at two different positions
if nums[i] == nums[j] {
return true
}
}
}
return false
}
C#Tested in our runner
public class Solution {
public bool containsDuplicate(int[] nums) {
int n = nums.Length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// same value at two different positions
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}
Approach 2: Sort, then compare neighbours
What's slow: the brute force asks "is there an equal value anywhere else?" for each element, and answers by scanning the whole array again. Most of those comparisons are between values that are far apart in size and could never match.
The insight that fixes it: after sorting, equal values sit next to each other. A duplicate exists exactly when some adjacent pair is equal, so one linear scan replaces the nested loops. The sort is the only expensive part.
Steps
- Copy
numsso the caller's array is not reordered. - Sort the copy in ascending order.
- Loop
ifrom 1 to n - 1. - If
sorted[i] == sorted[i - 1], return true. - If the loop ends, return false.
Dry run
On [-1000000000, 1000000000]:
- Copy and sort. The array is already ordered:
[-1000000000, 1000000000]. i = 1: comparesorted[1] = 1000000000withsorted[0] = -1000000000. They differ.- The loop ends, so return
false.
On [8, 3, 5, 8] the sorted copy is [3, 5, 8, 8]. The scan reaches i = 3, sees 8 == 8, and returns true.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Here n is the array length. Comparison sorting costs O(n log n), and the neighbour scan makes at most n - 1 comparisons, so the sort dominates. The copy holds n integers, which is O(n) space. Sorting the input in place would drop the copy but would reorder the caller's data.
PythonTested in our runner
from typing import List, Optional
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
ordered = sorted(nums) # sorted() returns a new list
for i in range(1, len(ordered)):
# equal values are adjacent after sorting
if ordered[i] == ordered[i - 1]:
return True
return False
JavaTested in our runner
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
int[] ordered = nums.clone();
Arrays.sort(ordered);
for (int i = 1; i < ordered.length; i++) {
// equal values are adjacent after sorting
if (ordered[i] == ordered[i - 1]) {
return true;
}
}
return false;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
vector<int> ordered = nums; // copy, so the input is untouched
sort(ordered.begin(), ordered.end());
for (size_t i = 1; i < ordered.size(); i++) {
// equal values are adjacent after sorting
if (ordered[i] == ordered[i - 1]) {
return true;
}
}
return false;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
const ordered = [...nums];
// a default sort() compares as strings, so pass a numeric comparator
ordered.sort((a, b) => a - b);
for (let i = 1; i < ordered.length; i++) {
// equal values are adjacent after sorting
if (ordered[i] === ordered[i - 1]) {
return true;
}
}
return false;
};
GoTested in our runner
import "sort"
func containsDuplicate(nums []int) bool {
ordered := make([]int, len(nums))
copy(ordered, nums)
sort.Ints(ordered)
for i := 1; i < len(ordered); i++ {
// equal values are adjacent after sorting
if ordered[i] == ordered[i-1] {
return true
}
}
return false
}
C#Tested in our runner
public class Solution {
public bool containsDuplicate(int[] nums) {
int[] ordered = (int[])nums.Clone();
System.Array.Sort(ordered);
for (int i = 1; i < ordered.Length; i++) {
// equal values are adjacent after sorting
if (ordered[i] == ordered[i - 1]) {
return true;
}
}
return false;
}
}

Solution pattern
Hashing - Previously Seen / Existence Check
Approach 3: One-pass hash setOptimalHashing - Previously Seen / Existence Check
What's slow: sorting does more work than the question needs. You pay O(n log n) to put every value in order, but you only need to know whether a value was met before. Order is information you never use.
The insight that fixes it: a hash set stores values and answers "is this value present?" in O(1) on average. Walk the array once and check the set before inserting the current value. A hit means an earlier element is equal, so return true. A miss means the value is new, so insert it and move on.
Why it is correct. Before reading each element, the set holds exactly the values seen so far. If the current value is in the set, an earlier equal value exists, so true is correct. If the loop finishes without a hit, no value ever repeated, so false is correct.
Steps
- Create an empty set
seen. - Loop over each value
xinnums, left to right. - If
xis already inseen, return true. - Otherwise add
xtoseen. - After the loop ends, return false.
Dry run
Trace on [-1000000000, 1000000000]. The set starts empty.
| Step | Value read | In seen before? | Action | seen after |
|---|---|---|---|---|
| 0 | none | n/a | start | {} |
| 1 | -1000000000 | no | insert | {-1000000000} |
| 2 | 1000000000 | no | insert | {-1000000000, 1000000000} |
| end | none | n/a | loop finished | return false |
No lookup ever hit, so every value is distinct and the answer is false.
For contrast, trace [8, 3, 5, 8]. After reading 8, 3 and 5 the set holds {8, 3, 5}. The fourth value is 8, the lookup hits, and the function returns true without reading further.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the array length. The loop runs at most n times, and each iteration does one lookup and at most one insert, each O(1) on average. Total time is O(n) on average. The set holds at most one entry per distinct value, so with all values distinct it holds n entries and uses O(n) space. A very bad hash function could degrade lookups, but standard library hashes for integers behave well in practice.
PythonTested in our runner
from typing import List, Optional
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for x in nums:
# check before inserting, or every value matches itself
if x in seen:
return True
seen.add(x)
return False
JavaTested in our runner
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums) {
// check before inserting, or every value matches itself
if (seen.contains(x)) {
return true;
}
seen.add(x);
}
return false;
}
}
C++Tested in our runner
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
seen.reserve(nums.size()); // avoids repeated rehashing
for (int x : nums) {
// check before inserting, or every value matches itself
if (seen.count(x)) {
return true;
}
seen.insert(x);
}
return false;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
const seen = new Set();
for (const x of nums) {
// check before inserting, or every value matches itself
if (seen.has(x)) {
return true;
}
seen.add(x);
}
return false;
};
GoTested in our runner
func containsDuplicate(nums []int) bool {
seen := make(map[int]struct{}, len(nums))
for _, x := range nums {
// check before inserting, or every value matches itself
if _, ok := seen[x]; ok {
return true
}
seen[x] = struct{}{}
}
return false
}
C#Tested in our runner
public class Solution {
public bool containsDuplicate(int[] nums) {
var seen = new HashSet<int>();
foreach (int x in nums) {
// check before inserting, or every value matches itself
if (seen.Contains(x)) {
return true;
}
seen.Add(x);
}
return false;
}
}
Common mistakes
- Inserting before the lookup:
seen.add(x)followed byif x in seen. The value always finds itself, so every non-empty array returns true. Check first, then insert. - Using a list as the "seen" container:
if x in seen_list. The membership test is O(k) and the total goes back to O(n^2). Use a set. - Starting the inner brute-force loop at
j = iinstead ofj = i + 1. Each element then equals itself and the answer is always true. Start ati + 1. - Calling
sort()in JavaScript without a comparator. The default order is by string, so10sorts before9. Equal values still end up adjacent, but a numeric comparator(a, b) => a - bavoids confusion and keeps the order meaningful. - Comparing
sorted[i]withsorted[i + 1]and looping ton. The last iteration reads past the end. Loopifrom 1 and compare withi - 1, or stop atn - 2. - Returning false inside the loop on the first miss, for example
else: return False. One distinct pair says nothing about later elements. Return false only after the loop finishes.
Edge cases
[5]: one element. No pair exists, so return false. Brute force and sorting loops run zero times.[6, 6]: the smallest array with a duplicate. Return true on the second element.[-1000000000, 1000000000]: extreme values that differ. Return false. A comparator that subtracts values could overflow in Java or C#, so compare for equality only.[1, 2, 3, 1]: the duplicate is the first and last element. Sorting finds it after reordering. The hash set finds it only on the final step.[0, 0, 0, 0]: many copies. Return true as soon as the second 0 is read.- Maximum size with all distinct values (10^5 elements): the worst case for every approach. Brute force is too slow here. The set holds 10^5 entries.
Follow-ups interviewers ask
- Can you solve it in O(1) extra space?
- Sort the input in place and scan neighbours. That uses O(1) extra memory beyond the sort's own stack, and runs in O(n log n) time. The cost is that you reorder the caller's array. If you must not mutate it, you need O(n) for a copy, so the trade is time for space.
- What if the array does not fit in memory?
- Use an external sort: sort chunks that fit in memory, write them to disk, then merge them and compare adjacent values in the merged stream. Or hash each value into one of many buckets on disk, then check each bucket on its own with a set. Equal values always land in the same bucket, so each bucket is independent.
- What if you must find a duplicate within k positions of each other?
- That is Contains Duplicate II. Keep a map from value to its latest index, or a set holding only the last k values. When you slide forward, remove the value that is now k + 1 positions behind. The check stays O(1) per element and space drops to O(k).
Contains Duplicate FAQ
What is the time complexity of Contains Duplicate?
The one-pass hash set runs in O(n) average time and O(n) space. Sorting then scanning neighbours runs in O(n log n) time. Comparing every pair runs in O(n^2) time and O(1) space. For n up to 10^5, the hash set is the standard answer.
Why use a hash set for Contains Duplicate?
The problem needs only a membership test: has this value appeared earlier? A hash set answers that in O(1) on average and stores nothing else. That turns n lookups into a single linear scan, with no sorting and no pair comparisons.
Can Contains Duplicate be solved in O(1) extra space?
Yes, but only by trading time. Sort the array in place and compare neighbours, which takes O(n log n) time and mutates the input. Without modifying the array, the brute force is O(1) space but O(n^2) time. No known approach gets O(n) time and O(1) extra space for arbitrary integers in this range.
Does the order of checking and inserting matter?
Yes. Check whether the value is in the set first, then insert it. If you insert first, the check always succeeds because the value just added matches itself, and the function wrongly returns true.
How do you solve LeetCode 217 in Python in one line?
Compare lengths: len(set(nums)) != len(nums). It is correct and has the same O(n) time and space. It always builds the full set, so it cannot stop early the way the loop version does when a duplicate appears near the start.
Which Contains Duplicate approach should I give in an interview?
Mention the brute force briefly, state its O(n^2) cost, then give the hash set as the answer. Name the sorting approach as the alternative when memory is tight. That shows you know the trade-off between time and space.
Asked at
See which companies ask this — Pro
Related problems
- Happy Number · same technique: Hashing - Previously Seen / Existence Check
- Linked List Cycle · same technique: Hashing - Previously Seen / Existence Check
- Contains Duplicate II · same technique: Hashing - Previously Seen / Existence Check
- Design HashSet · same technique: Hashing - Previously Seen / Existence Check
- Intersection of Two Arrays · same technique: Hashing - Previously Seen / Existence Check
- Longest Substring Without Repeating Characters · next harder, same pattern
- Two Sum · same pattern: Array/Matrix Manipulation Patterns
- Valid Anagram · same pattern: Array/Matrix Manipulation Patterns
- Plus One · same pattern: Array/Matrix Manipulation Patterns
- Missing Number · same pattern: Array/Matrix Manipulation Patterns