Skip to content
Problem 442 · LeetCode 442(opens in a new tab)

Find All Duplicates in an Array

MediumArrays

You get an array nums of length n. Every value in it is a whole number from 1 to n, and no value shows up more than twice.

Return every value that shows up exactly twice, in any order. Aim for O(n) time and only O(1) extra memory beyond the list you return.

Example 1

Input:  nums = [5, 2, 6, 2, 1, 5]
Output: [2, 5]
Why:    2 and 5 each appear twice
2 more examples and the constraints

Example 2

Input:  nums = [3, 1, 3]
Output: [3]
Why:    only 3 repeats

Example 3

Input:  nums = [1]
Output: []
Why:    one number cannot repeat

Constraints

  • 1 ≤ n ≤ 100,000, where n is the length of nums
  • 1 ≤ nums[i] ≤ n
  • Each value appears once or twice

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort, then compare neighboursO(n log n)
  2. Hash setO(n)
  3. Mark slots by signO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Sort, then compare neighboursO(n log n)
Works; too slow and copies
Hash setO(n)
Passes; O(n) extra memory
Mark slots by signO(n)
Best; no extra memory

n = length of nums.

Edge cases to test

  • A single number. [1] has no repeats, so return [].
  • No repeats at all. [4, 2, 1, 3] flips every slot once and returns [].
  • Every value twice. [2, 1, 3, 1, 2, 3] returns all three values.
  • The value n. It maps to the last slot, n − 1, so the index stays in range.

Common mistakes

  • Using nums[i] − 1 as the slot without abs, after that cell was already flipped negative.
  • Adding the slot's value to the result instead of the value you read.
  • Forgetting that values start at 1, and using slot v instead of v − 1.

How to talk through it

  1. 1Clarify. Are values always between 1 and n? Can a value show up three times? May I change the input?
  2. 2Give the simple answer. A hash set finds repeats in one pass; say it costs O(n) extra memory.
  3. 3Use the value range. Values 1 to n fit the n indexes exactly, so the array can be its own set.
  4. 4Code the sign flip. Explain why you read with abs and why a negative slot means a repeat.
  5. 5Test out loud. Run [1], a list with no repeats, and one where every value repeats.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?