awelgorithms

Catch up with the trail pointer

Updated

Catching up is L += 1 while R stays. Repeat until L reaches the lead, or until the rule stops. The trail consumes cells the lead already passed.

What to focus on

After each catch-up step L is the old L+1, R is unchanged, and L ≤ R. The trail must not pass the lead.

Worked examples

one step

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

Result: L=1, R=2

caught up

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

Result: L=2, R=2

already together

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

Result: L=0, R=0 · refuse

Try it

Write catchUp(a, L, R). a is an array of integers. L is the trail index. R is the lead index. Do L += 1. Print L and R after each step. Return nothing. 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.