Skip to content
Optimal Lab

Arrays & Hashing · 002Easy

Contains Duplicate

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

Constraints

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

Examples

containsDuplicate([1, 2, 3, 1])   ->  true
containsDuplicate([1, 2, 3, 4])   ->  false
containsDuplicate([1])            ->  false   // single element
containsDuplicate([1, 1])         ->  true   // smallest possible duplicate
containsDuplicate([5, 5, 5, 5])   ->  true   // all identical
containsDuplicate([-1, 0, 1, 2])  ->  false   // negatives and zero are distinct values

Edge cases

  • Single-element array — always false.
  • All elements identical.
Show the target complexity (spoiler)
Naive
O(n^2) time, O(1) space — compare every pair.
Target
O(n) time, O(n) space — insert into a Set and stop at the first collision.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/01-arrays-hashing/002-contains-duplicate.js
./practice c 002

Stuck? Watch the pattern run