Community Problem

Find All Duplicates in an Array

Difficulty: Medium

Identify every value that appears twice in an array of integers in [1, n], using O(1) extra space via index-negation.

Find All Duplicates in an Array

Identify every value that appears twice in an array of integers in [1, n], using O(1) extra space via index-negation.

MEDIUM
Free
arrays
hash-table
two-pointers
arjunrivera

By @arjunrivera

January 31, 2026

·

Updated May 18, 2026

927 views

29

Rate

I keep this one bookmarked for the moment a candidate finishes a hash-set duplicate detector and tells me "that is the optimal answer." The constraint that values fall in [1, n] and that the array length is n is doing all the work, because it lets you treat the array itself as a hash table by flipping the sign at the index each value points at. The official catalog has Find the Duplicate Number (one duplicate, read-only constraint, Floyd cycle) but skipped the every-duplicate variation that the negation trick handles cleanly.

Find All Duplicates in an Array

Given an integer array nums of length n where every value satisfies 1 <= nums[i] <= n, return an array of all the integers that appear twice in nums. Each integer appears either once or twice. The output may be returned in any order.

Examples

Example 1:

  • Input: nums = [4, 3, 2, 7, 8, 2, 3, 1]
  • Output: [2, 3] (any order)
  • Explanation: 2 and 3 appear twice; the rest appear once.

Example 2:

  • Input: nums = [1, 1, 2]
  • Output: [1]
  • Explanation: Only 1 appears twice.

Example 3:

  • Input: nums = [1]
  • Output: []
  • Explanation: A single element cannot be duplicated.

Example 4:

  • Input: nums = [2, 2]
  • Output: [2]
  • Explanation: The single value 2 appears twice.

Constraints

  • n == nums.length
  • 1 <= n <= 10^5
  • 1 <= nums[i] <= n
  • Each element appears once or twice.

Follow-up

The natural hash-set solution is O(n) time and O(n) space. Can you do it in O(n) time and O(1) extra space (excluding the output array)? The classic trick uses the input array itself as the bookkeeping structure by negating the value at the index that each nums[i] points to. Treat that as a hint, not a requirement.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems