15% off all plans & roadmaps Use code

See plans

Contains 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^9
  • nums contains only integers.

Constraints that matter

  • nums.length up 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.length is 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Loop i from 0 to n - 1.
  2. For each i, loop j from i + 1 to n - 1.
  3. If nums[i] == nums[j], return true.
  4. If both loops finish, return false.

Dry run

On [-1000000000, 1000000000], n is 2.

  • i = 0: j runs from 1 to 1. Compare -1000000000 with 1000000000. They differ.
  • i = 1: j starts 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

TimeO(n^2)
SpaceO(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

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

  1. Copy nums so the caller's array is not reordered.
  2. Sort the copy in ascending order.
  3. Loop i from 1 to n - 1.
  4. If sorted[i] == sorted[i - 1], return true.
  5. If the loop ends, return false.

Dry run

On [-1000000000, 1000000000]:

  • Copy and sort. The array is already ordered: [-1000000000, 1000000000].
  • i = 1: compare sorted[1] = 1000000000 with sorted[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

TimeO(n log n)
SpaceO(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
Hashing - Previously Seen / Existence Check pattern infographic for Contains Duplicate

Solution pattern

Hashing - Previously Seen / Existence Check

Part of Array/Matrix Manipulation Patterns

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

  1. Create an empty set seen.
  2. Loop over each value x in nums, left to right.
  3. If x is already in seen, return true.
  4. Otherwise add x to seen.
  5. After the loop ends, return false.

Dry run

Trace on [-1000000000, 1000000000]. The set starts empty.

StepValue readIn seen before?Actionseen after
0nonen/astart{}
1-1000000000noinsert{-1000000000}
21000000000noinsert{-1000000000, 1000000000}
endnonen/aloop finishedreturn 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

TimeO(n)
SpaceO(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

Common mistakes

  • Inserting before the lookup: seen.add(x) followed by if 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 = i instead of j = i + 1. Each element then equals itself and the answer is always true. Start at i + 1.
  • Calling sort() in JavaScript without a comparator. The default order is by string, so 10 sorts before 9. Equal values still end up adjacent, but a numeric comparator (a, b) => a - b avoids confusion and keeps the order meaningful.
  • Comparing sorted[i] with sorted[i + 1] and looping to n. The last iteration reads past the end. Loop i from 1 and compare with i - 1, or stop at n - 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

Practise it