awelgorithms

Skip a dropped value without writing

Updated

When a[i] is dropped, only i++. Do not write. Do not touch w. The dropped slot becomes gap junk in [w, i).

What to focus on

w is unchanged. The value at a[i] is never copied. Later writes may overwrite it because it is already read.

Worked examples

leading zero

a = [0, 1, 0, 9], keep nonzero, i=0 w=0
  1. a[0]=0 drop
  2. no write
  3. i 0→1, w stays 0

Result: w=0, gap is index 0

middle zero

a = [1, 1, 0, 9], keep nonzero, i=2 w=1
  1. a[2]=0 drop
  2. w stays 1
  3. i 2→3

Result: w=1, a still [1, 1, 0, 9]

drop 1

a = [4, 1, 9, 1], keep ≠ 1, i=1 w=1
  1. a[1]=1 drop
  2. no write
  3. w stays 1

Result: logical prefix still [4]

Try it

Write skipDrop(a, i, w). a is an array of integers. i is the read index of a dropped value. w is the write index with w ≤ i. Advance i only. Do not write. Print w to prove it did not move. Return nothing. For a = [0, 1, 0, 9] keep nonzeros, list every dropped i. Repeat for keep ≠ 1 on [4, 1, 9, 1].

a is nonempty. a[i] is a dropped value. w ≤ i.