awelgorithms

Grow the gap between pointers

Updated

Growing the gap advances only the lead: R += 1. Distance R - L increases by 1. The trail stays put.

What to focus on

After the move, R - L is one larger, L is unchanged, and R < n. Growing from a meeting cell is how a same-direction scan starts.

Worked examples

from zero

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

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

again

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

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

one

a = [7], L=0, R=0
  1. start L=0, R=0
  2. R += 1 would be 1, out

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

Try it

Write growGap(a, L, R). a is an array of integers. L is the trail index. R is the lead index. Gap is R - L. Do R += 1. Print gap after each move. Return nothing. On [4, 1, 9] from (0, 0) then (0, 1), and on [4, 1, 9, 1] from (0, 2).

a has length ≥ 3. R starts strictly before the last index.