#448

Find All Numbers Disappeared in an Array

Easy Index marking

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

?The problem

An array of n numbers has values in 1..n, some repeated. Return all values in 1..n that never appear, using no extra space besides the output.

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

◎Understanding

Really asking: values are 1..n; which of them never appear?

Why this works: use the array as its own checklist. Seeing value v flips nums[v-1] negative. Positions that stay positive were never "visited".

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

after marking: [-4, -3, -2, -7, 8, 2, -3, -1]index 4 and 5 still positive → 5 and 6 are missing

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using nums[i] - 1 as the index after it was negated. Use Math.abs(nums[i]).