ToolMight Logo
EasyArrays & HashingHash SetSorting ScanFrequency Tracking

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Optimal Time
O(n)
Optimal Space
O(n)
Primary Pattern
Hash Set
Visualizer
Open Interactive View →

Problem Statement

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

Examples & Constraints

Example 1
Input: nums = [1, 2, 3, 1]
Output: true
Explanation: The element 1 occurs at index 0 and index 3, satisfying the duplicate condition.
Example 2
Input: nums = [1, 2, 3, 4]
Output: false
Explanation: All elements are pairwise distinct, so no duplicates exist.
Constraints
  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Pattern Recognition & Core Invariant

How to Spot This Pattern

Existence or uniqueness checks over unordered values choose a Hash Set for O(n) average speed when extra space is permitted, or sorting + adjacent comparison when space is constrained.

Core Invariant

Either the first repeated item triggers an immediate match against previously inserted Hash Set members, or sorting places any equal elements in adjacent indices nums[i] == nums[i + 1].

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Hash Set (Early Termination Lookup)Optimal
O(n)O(n)Iterate through elements while inserting them into a hash set. If an element already exists, immediately return true in O(1) average time.
2. In-Place Sorting (Adjacent Scan)
O(n log n)O(1) to O(n)Sort the array first so identical values are grouped together, then scan adjacent elements in O(1) extra space.

1. Hash Set (Early Termination Lookup)

Optimal
TimeO(n)
SpaceO(n)

Iterate through elements while inserting them into a hash set. If an element already exists, immediately return true in O(1) average time.

Time ComplexityO(n)

We make at most a single pass over the array of N elements. Hash table lookups and insertions operate in O(1) average time.

Space ComplexityO(n)

In the worst case (when all elements are unique), the hash set stores all N numbers.

How It Works

The Core Mental Model: Instant Memory Lookback

When scanning an array sequentially, the naive human approach is to look ahead and compare every item with everything else. In software engineering, that forward scan leads to an unacceptable O(n²) nested loop.

Instead, we invert the question: "Have I seen this specific integer already?"

A Hash Set gives us average O(1) lookup and insertion:

  1. Initialize an empty hash set seen.
  2. For each number num in nums:
  • If num is already present in seen, return true immediately (early exit).
  • Otherwise, insert num into seen.
  1. If the loop completes without finding any repeated item, return false.

Engineering Trade-Off: Time vs Memory

This approach trades auxiliary memory (up to N items stored in a hash bucket table) to achieve lightning-fast linear O(n) runtime. For interview discussions, mention that if memory is strictly constrained (e.g. microcontrollers or embedded memory limits), in-place sorting avoids the O(n) allocation.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Inspect nums[0] = 1

Check hash set. 1 is not in set. Add 1 to set.

State:set = {1}
Strengths
  • +Optimal O(n) runtime
  • +Early exit terminates as soon as first duplicate is spotted
Trade-offs
  • -Consumes O(n) auxiliary heap memory for hash table buckets

Reference Implementation

Complete implementation for Hash Set (Early Termination Lookup) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def contains_duplicate(nums: list[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
if __name__ == "__main__":
test1 = [1, 2, 3, 1]
test2 = [1, 2, 3, 4]
print("test1 contains duplicate:", contains_duplicate(test1))
print("test2 contains duplicate:", contains_duplicate(test2))

2. In-Place Sorting (Adjacent Scan)

TimeO(n log n)
SpaceO(1) to O(n)

Sort the array first so identical values are grouped together, then scan adjacent elements in O(1) extra space.

Time ComplexityO(n log n)

Dominated by the comparison sort algorithm (QuickSort/TimSort). The subsequent adjacent pass is linear O(n).

Space ComplexityO(1) to O(n)

O(1) auxiliary memory if sorted in-place (in C/C++ via std::sort or qsort), or O(n) if copying or utilizing non-mutating sort.

How It Works

The Invariant: Clustered Identical Values

When an array is sorted in ascending order, any two identical numbers are guaranteed to sit directly adjacent to one another (nums[i] == nums[i + 1]).

  1. Sort the array using an in-place sorting algorithm (like QuickSort or Dual-Pivot Quicksort).
  2. Traverse from index 0 to n - 2.
  3. If nums[i] == nums[i + 1], return true.
  4. If no adjacent duplicates are found after examining all consecutive pairs, return false.

When to Prefer Sorting Over Hash Set

In embedded systems, gaming engines, or memory-critical kernels where allocating thousands of hash nodes would cause garbage collector pressure or memory fragmentation, sorting uses O(1) or O(log n) stack space.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Sort Array In-Place

Sort [1, 2, 3, 1] ascending into [1, 1, 2, 3] so duplicates sit side by side.

State:sorted = [1, 1, 2, 3]
Strengths
  • +Zero auxiliary hash table heap allocation
  • +Simple cache-friendly linear scan
Trade-offs
  • -Mutates original array order
  • -Slower runtime than Hash Set for large arrays

Reference Implementation

Complete implementation for In-Place Sorting (Adjacent Scan) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def contains_duplicate_sort(nums: list[int]) -> bool:
nums.sort()
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
return True
return False
if __name__ == "__main__":
nums = [1, 2, 3, 1]
print("Result:", contains_duplicate_sort(nums))
Interactive Visualizer

Trace Hash Table mechanics in memory

Step through custom inputs in the Hash Table visualizer to inspect pointer updates, array shifts, and call-stack state alongside Contains Duplicate.

Open Hash Table visualizer

Frequently Asked Questions

Why is Hash Set faster than sorting for Contains Duplicate?

A Hash Set runs in O(n) average time via O(1) lookups and exits as soon as the first repeat appears. Sorting runs O(n log n) comparisons upfront even if indices 0 and 1 are identical.

What is the space complexity if we sort in-place?

In-place sorting uses O(1) heap memory (plus O(log n) quicksort recursion frames in C++), avoiding O(n) hash-table memory when RAM is tight.

Can Python or JavaScript simply compare `set.size < nums.length`?

Yes, though inserting inside a loop with early return is strictly faster on inputs that duplicate early because it skips building the remaining set entries.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Single-element array ([42]) cannot contain two identical items and returns false.
  • Negative 32-bit extremes ([-10^9, -10^9]) hash identically without range overflow.
  • Large distinct arrays up to 10^5 elements still require full traversal before returning false.

Common Bugs to Avoid

  • Scanning for duplicates using nested loops (`O(n²)`), timing out around `n = 10^5`.
  • Mutating the caller's array via in-place sort when API requirements expect read-only input.
  • Scanning `i` up to `nums.length - 1` instead of `nums.length - 2` in the sorted adjacent check, causing out-of-bounds at `nums[i + 1]`.

Interview Follow-Up Variations

  • Contains Duplicate II: check if duplicate indices satisfy `abs(i - j) <= k` using a sliding-window Hash Set of max size k.
  • Contains Duplicate III: test `abs(nums[i] - nums[j]) <= valueDiff` within index gap k using bucket partitioning.

Related Problems

All problems
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyArrays & Hashing

Valid Anagram

Check whether string t is an anagram of string s. Compare O(n log n) canonical sorting against an O(n) fixed 26-letter frequency bucket balance.

Pattern: Frequency Counting
O(n) · O(1)
Solve
MediumArrays & Hashing

Product of Array Except Self

Compute the array of products excluding each element without division. Progress from separate left/right product arrays to O(1) auxiliary space.

Pattern: Prefix and Suffix Products
O(n) · O(1)
Solve