awelgorithms

Shrink the gap between pointers

Updated

Shrinking the gap in the same direction advances only the trail: L += 1. Distance R - L decreases by 1. This is not opposite-end R--.

What to focus on

After the move, R - L is one smaller, R is unchanged, and L ≤ R. Do not shrink when the gap is already 0.

Worked examples

from two

a = [4, 1, 9], L=0, R=2
  1. start L=0, R=2 · gap 2
  2. L += 1

Result: L=1, R=2 · gap 1

to zero

a = [4, 1, 9], L=1, R=2
  1. start L=1, R=2 · gap 1
  2. L += 1

Result: L=2, R=2 · gap 0

already zero

a = [4, 1, 9], L=0, R=0
  1. start L=0, R=0
  2. L += 1 would pass the lead

Result: L=0, R=0 · refuse

Try it

Write shrinkGap(a, L, R). a is an array of integers. L is the trail index. R is the lead index. Gap is R - L. Shrink by moving L, not R. Print gap R-L after each move. On [4, 1, 9] from (0, 2) then (1, 2), and on [4, 1, 9, 1] from (0, 3).

a has length ≥ 3. Start with L < R so the gap is positive.