awelgorithms

Count remaining cells between pointers

Updated

Inclusive cells in [L, R] are R-L+1. Exclusive cells strictly between are max(0, R-L-1). Empty remaining is L > R (crossed) or L == R (one cell, zero pairs).

What to focus on

After each move, recompute. The count only shrinks in an inward scan. A same-direction pair (i, w) uses i-w as the dropped gap.

Worked examples

full

a = [1, 4, 9], L=0 R=2
  1. R-L+1=3
  2. strict between=1 (the 4)

Result: 3 cells, 1 between

after R--

a = [1, 4, 9], L=0 R=1
  1. R-L+1=2
  2. strict between=0

Result: 2 cells, 0 between

compact gap

a = [0, 1, 0, 9], i=3 w=1
  1. unread+current from i is 1 cell
  2. dropped gap i-w=2

Result: gap 2, w lags by two drops

Try it

Write remaining(a, L, R). a is an array of integers. L is the left index. R is the right index. Inclusive count is R-L+1. Print R-L+1 at each inward pair, then i-w for compact. Return nothing. For a = [1, 4, 9] print at (0, 2), (0, 1), (1, 1). For compact on [0, 1, 0, 9] print i-w after each i.

a is nonempty. L ≤ R for the inward counts. i ≥ w for the compact gap.