#442

Find All Duplicates in an Array

Medium Index marking

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Values are in 1..n and each appears once or twice. Return every value that appears twice, in O(n) time and O(1) extra space.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: values 1..n, some appear twice — list them.

Why this works: visiting value v flips nums[v-1] negative. If it's already negative, we've seen v before.

Example: [4, 3, 2, 7, 8, 2, 3, 1]

4,3,2,7,8 mark their slots2 again → slot 1 already negative → duplicate 23 again → slot 2 already negative → duplicate 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting Math.abs when reading a value that was already negated.