awelgorithms

Stop when the pointers cross

Updated

Crossing means L > R. The unprocessed slice is empty. Loops that run while L < R stop when the next inward step would make L > R.

What to focus on

The last legal pair was the step when L < R. After an L++ and R-- that yields L > R, do not read a[L] and a[R] as a pair.

Worked examples

even

a = [4, 1, 9, 1]
  1. start L=0, R=3
  2. close → L=1, R=2
  3. close → L=2, R=1

Result: crossed · L=2, R=1

two

a = [4, 1]
  1. start L=0, R=1
  2. close once

Result: L=1, R=0 · crossed

empty

a = []
  1. no indices
  2. treat as already empty, not a pair

Result: no pair · already empty

Try it

Write stopOnCross(a). a is an array of integers. L is the left index, start 0. R is the right index, start n-1. After each close print L and R. Halt when L > R and do not read that pair. On [4, 1, 9, 1] end at L=2, R=1. On [4, 1] end at L=1, R=0. On [4, 1, 9, 1, 7, 2] end at L=3, R=2.

a has even length ≥ 2. Start with L = 0, R = n-1.