Contains Duplicate solution explained
Contains Duplicate asks whether any value occurs more than once in a list, and the standard solution walks the list once with a hash set, returning true the moment a value is already in the set. That runs in O(n) average time with O(n) extra memory; sorting first and comparing neighbors is the fallback when memory is tight.
By Evin JohnPublished 8 min read
Restating the task
You get a list of whole numbers. Decide whether at least one number is present two or more times. The output is a single true or false, not the repeated value and not where it sits. A list with no entries, or with one, cannot contain a repeat. That is the whole problem, which is exactly why the interesting part is the discussion of trade-offs around it.
| List | Result | Why |
|---|---|---|
| [5, 8, 2, 9, 8] | true | 8 shows up at positions 1 and 4 |
| [7, 3, 9] | false | Three different values |
| [-2, 4, -2, 0] | true | Negative numbers repeat like any other value |
| [] | false | Nothing to compare |
| [6, 6, 6, 6] | true | Several copies still only mean true |
Questions to settle first: how long can the list get, and could it be too large to hold in memory alongside a second structure? Are the values in a small known range? May you reorder the input? The answers decide between the hash set, the sort, and a counting array, and asking them out loud is most of what makes this a real interview question rather than a one-liner.
What the interviewer is checking
Few people fail to solve it. The signal is in how you compare options. A strong answer names three approaches, gives each its time and memory cost, and explains which one you would ship under which constraint. It also notices the early exit: if a repeat sits near the front of a huge list, a loop with a set stops in a handful of steps, while building a full set of the list first does not. Interviewers use this problem as a warm-up, then pivot to a variant that needs a window or a sort.
Common extensions
- Repeat within k positions. Report true only if two equal values sit at most k indexes apart. Keep a map of each value's latest index, or a set that holds just the last k values. Code is further down.
- Close values, close positions. True if two entries differ in value by at most t and in position by at most k. Bucket values by width t + 1 inside a sliding window, or keep a sorted window and check the neighbors of each new value.
- Return the repeated value. Same loop, return the value instead of true.
- Values known to lie between 1 and n. A boolean array of size n + 1 replaces the hash set and avoids hashing altogether.
- Data that does not fit in memory. Sort it externally in chunks and scan neighbors, or hash values into files by range and check each file alone. A Bloom filter can rule out repeats cheaply but gives false positives, so every hit still needs a check.
Brute force: compare every pair
Take each entry and compare it with every entry after it. Return true on the first equal pair, false if none turn up. It uses no extra memory, takes O(n²) time, and is the correct reference to test faster versions against.
def has_repeat_slow(values):
for i in range(len(values)):
for j in range(i + 1, len(values)):
if values[i] == values[j]:
return True
return FalseMiddle ground: sort, then look at neighbors
Once a list is sorted, equal values must be adjacent. One pass comparing each element with the one before it finds any repeat. The cost is dominated by the sort, O(n log n). Sorting a copy keeps the caller's list intact but costs O(n) memory; sorting in place keeps extra memory to whatever the sort itself uses, at the price of changing the input. Say which one you are doing.
def has_repeat_sorted(values):
ordered = sorted(values)
for i in range(1, len(ordered)):
if ordered[i] == ordered[i - 1]:
return True
return FalseOptimal for time: a hash set with an early exit
Walk the list and keep a set of every value seen so far. Before adding a value, check whether it is already there. If it is, you have found a repeat and can stop. If you reach the end, there was none. Each membership check and insert is O(1) on average, so the loop is O(n) time and the set uses up to O(n) memory.
def has_repeat(values):
seen = set()
for v in values:
if v in seen:
return True
seen.add(v)
return Falsefunction hasRepeat(values) {
const seen = new Set();
for (const v of values) {
if (seen.has(v)) return true;
seen.add(v);
}
return false;
}The short version, comparing the size of a set built from the list with the size of the list, is correct and worth mentioning. It always processes the whole list, though, so it gives up the early exit. In an interview, write the loop and mention the one-liner as an alternative.
def has_near_repeat(values, k):
last_at = {}
for i, v in enumerate(values):
if v in last_at and i - last_at[v] <= k:
return True
last_at[v] = i
return FalseOverwriting the stored index on every visit is what makes the window version correct: the closest earlier copy is always the most recent one, so it is the only one worth comparing against.
Comparing the options
| Approach | Time | Extra space | Best when |
|---|---|---|---|
| Every pair | O(n²) | O(1) | The list is tiny, or you need a test oracle |
| Sort, then neighbors | O(n log n) | O(1) in place, O(n) for a copy | Memory is tight and reordering is allowed |
| Hash set with early exit | O(n) average | O(n) | Speed matters most, the default answer |
| Boolean array by value | O(n) | O(range of values) | Values fall in a small known range |
| Latest-index map, k window | O(n) average | O(n), or O(k) with a window set | Repeats only count when they are close |
Edge cases to run through
- An empty list and a single-element list both return false.
- The repeat sits at the very end, so the loop runs to the last element before finding it.
- The repeat sits at the start, which is where the early exit pays off.
- Negative values and zero mixed together.
- All entries equal.
- For the window follow-up: k of 0 should always give false, since two different positions are at least 1 apart.
Where answers go wrong
- Calling the sort approach O(1) space without saying whether the input is sorted in place and what the sort uses internally.
- Using a plain JavaScript object as the set. Keys become strings, which is harmless for whole numbers but surprising once the data mixes types.
- Saying the set is O(1) per operation in the worst case. It is O(1) on average; heavy collisions can degrade it.
- In the window variant, keeping the first index of each value instead of the latest. A far-off early copy then hides a near one.
- Skipping the trade-off discussion. On a problem this short, the comparison is the answer.
How to explain it out loud
Fictional example
- Candidate
- Comparing all pairs works but is quadratic. If I sort, equal values end up next to each other, so one scan finds a repeat in n log n, with little extra memory if I may sort in place.
- Candidate
- If memory is fine, a set is faster: I check each value against the set, return true on a hit, otherwise add it. That is linear on average and stops early when a repeat comes up front.
- Candidate
- On 5, 8, 2, 9, 8 the set holds 5, 8, 2 and 9 when the second 8 arrives, so I return true at index 4.
Related walkthroughs
A set of seen values is the same tool Two Sum uses with a dictionary, and Linked List Cycle can be solved by storing visited nodes in exactly this kind of set before you learn the two-pointer trick. Skipping repeated values after a sort is a key step in 3Sum, and a running summary of the past drives Best Time to Buy and Sell Stock. See every problem on the coding problems hub.
Natively as a study aid
Natively is a desktop app for Mac and Windows. When you drill warm-up problems like this one, it can read the prompt from a screenshot and lay out an approach with code, which is handy for checking whether you covered the sort and the set before peeking. It also transcribes your mock interviews, so you can hear whether you actually stated the memory cost. The AI assistant for coding interviews page has the details.
Questions people ask
What is the best solution for Contains Duplicate?
Loop once with a hash set. If the current value is already in the set, return true; otherwise add it. That is O(n) average time and O(n) extra space, and it stops at the first repeat.
Can you solve Contains Duplicate without extra memory?
Yes, by sorting the list in place and comparing each element with its neighbor. That costs O(n log n) time and changes the input, so ask first whether reordering is allowed.
Is comparing len(set(nums)) with len(nums) a good answer?
It is correct and short, but it always builds the whole set, so it loses the early exit. Mention it, then write the loop if the interviewer wants to see the reasoning.
How do you check for duplicates within k positions?
Keep a map from each value to the index where you last saw it. When a value comes back and the gap to its last index is at most k, return true; otherwise update the stored index.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
