Contains Duplicate

Easy

Topics
ArrayHash TableSorting

Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.

Example 1

10213213
The shaded cells hold the same value at two indices, so the answer is true.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,3,1]
Output: true

Example 2

10213243
Every value appears once, so the answer is false.
Input:  nums = [1,2,3,4]
Output: false

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

A value is a duplicate the moment we see it a second time. A hash set gives O(1) membership tests, so we can detect a repeat as soon as it occurs instead of comparing all pairs.

Approach

  1. Create an empty set.
  2. For each number, if it is already present, return True immediately.
  3. Otherwise insert it. If the loop finishes, all values were distinct → return False.

Walkthrough

nums = [1, 2, 3, 1]
1 -> add {1}
2 -> add {1,2}
3 -> add {1,2,3}
1 -> already in set -> return True

Complexity

  • Time — O(n): single pass with O(1) average set operations.
  • Space — O(n): the set may grow to hold every element.

Common Pitfalls

  • Sorting first (O(n log n)) also works and uses O(1) extra space — a good trade-off to mention if asked to avoid the hash set.

Full Solution — all languages

class Solution:
    def containsDuplicate(self, nums):
        seen = set()
        for v in nums:
            if v in seen:
                return True
            seen.add(v)
        return False
SensAI
Beta
Tap the mic to stop voice mode