Arrays & Hashing

Hash Set Lookup

Contains Duplicate

1Question

Contains Duplicate

EasyLeetCode 217 ↗

You are given an array of numbers called nums. Return true if any number appears at least two times. Return false if every number is different.

What counts as a duplicate?

Two positions with the same value. They do not need to be next to each other.
In [1, 2, 3, 1] the 1 at index 0 and the 1 at index 3 are duplicates.

Examples
Example 1
Input: [1,2,3,1]
Output: true

The number 1 appears at index 0 and at index 3.

Example 2
Input: [1,2,3,4]
Output: false

All four numbers are different.

Example 3
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

Many numbers repeat. We can stop at the first repeat we find.

Constraints

1 ≤ nums.length ≤ 105

Up to 100,000 numbers. Comparing every pair is about 5 billion checks, which is too slow. We want O(n).

−109 ≤ nums[i] ≤ 109

Numbers can be very big or negative, so we can not use them as list positions (no “counting array”). A hash set works for any value.

Follow-up

If memory is tight, sorting first gives O(n log n) time with little extra space.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Hash Set Lookup

Trade a little memory for a lot of speed.

A hash set stores values so that checking x in seen takes constant time on average. Instead of looking back through the whole array, we ask the set:

if num in seen: return True → else: seen.add(num)

Each number is checked once and added once. That turns an O(n²) search into one O(n) pass.

How to spot this pattern

  • The question asks “have I seen this before?”
  • You need to find repeats, pairs or missing values.
  • Order does not matter, only membership.
  • You are allowed O(n) extra memory.

4Explanation

The big idea: Walk through the array one number at a time and keep a set called seen. At every number there are only two cases:

Case 1: Already seen

The number is in seen. We found a duplicate. Return True right away.

Case 2: New number

The number is not in seen. Add it, and move to the next number.

If the loop ends without finding a repeat, every number was different, so return False.

Why is it correct? When we reach a number, seen holds exactly the numbers before it. So “in seen” means “appeared earlier”, which is the definition of a duplicate.

5Brute Force

Compare every pair of numbers.

Idea

A pair is fixed by two positions i and j with i before j. So we:

  • Pick every first position i.
  • Compare it with every later position j.
  • If the two values are equal, return true.
Python
def contains_duplicate_brute(nums):
    n = len(nums)

    for i in range(n):
        for j in range(i + 1, n):
            if nums[i] == nums[j]:  # same value at two positions
                return True

    return False


print(contains_duplicate_brute([1, 2, 3, 1]))  # True

6Optimal Solution

One pass with a hash set.

Python
def contains_duplicate(nums):
    seen = set()            # numbers we have already visited

    for num in nums:
        if num in seen:     # O(1) on average
            return True
        seen.add(num)

    return False


print(contains_duplicate([1, 2, 3, 1]))  # True

7Time and Space Complexity

Let n be the number of items in the array.

Brute force

Time: O(n²)Space: O(1)

Optimal (hash set)

Time: O(n)Space: O(n)

How big is the difference?

Approximate number of steps:

nBrute force (n²/2)Hash set (n)
104510
1,000499,5001,000
100,000about 5 billion100,000

The set uses more memory, but for 100,000 numbers it does around 50,000 times less work.

8Visualization

Try:Use 1 to 15 whole numbers (from -99 to 99), separated by commas.
Current Element-
Seen Set Size-
Duplicate?-
1
2
3
1

Step Analysis

Click "Next" to begin analysis.
Core Logic:
If num in seen: return True
Else: seen.add(num) and move on