🎉 All 30 days are live — the full DSA-30 course, from Big-O to System Design. See the roadmap →

Contains Duplicate easy

Description

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

Examples

> Case 1:
    Input:  nums = [1, 2, 3, 1]
    Output: true
 
> Case 2:
    Input:  nums = [1, 2, 3, 4]
    Output: false
 
> Case 3:
    Input:  nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
    Output: true

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

The naïve approaches

  • Nested loops — compare every pair. O(n²). Slow.
  • Sort first, then walk — O(n log n) time, O(1) extra space if you can mutate the input.
  • Hash set — O(n) time, O(n) space.

For interview purposes, the hash-set version is the canonical answer. It’s the simplest and fastest.

Intuition

Walk the array. For each element, ask the set “have I seen you?”. If yes, return true. If no, add it and continue. After the loop, no duplicate exists.

Try it yourself

Contains Duplicate — return true if any value repeats
Hint
Keep a set of values you've seen. For each element, return True the moment you find it already in the set; otherwise add it.
Reveal solution

Code

Java’s Set.add() returns false when the element was already in the set. That’s a useful idiom — it folds “check + insert” into one operation. Python’s set.add() returns nothing but you can use x in seen first; the cost is identical in practice.

A nice trick — the one-liner

Python’s set constructor deduplicates as it builds. So:

def contains_duplicate(nums):
    return len(set(nums)) != len(nums)

If the set has fewer elements than the list, there was a duplicate. It’s a delightful one-liner but uses more memory than needed — it processes the entire array before short-circuiting. In an interview, write the loop version; in a code review, write the one-liner.

Analysis

ApproachTimeSpace
Brute forceO(n²)O(1)
Sort + scanO(n log n)O(1)
Hash setO(n)O(n)

A textbook “trade space for time” — if you can spend O(n) extra memory, you save O(log n) per element.

Finished this page?