awelgorithms

Stop when the pointers meet

Updated

Meeting means L == R. The remaining cell is the middle. Opposite-end loops that process pairs with L < R halt here. They do not pair the middle with itself.

What to focus on

Halt when L == R. Do not L++ or R-- past the meeting cell unless crossing is the halt rule. n = 1 starts already met. Even n is not yet met after one close.

Worked examples

odd

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

Result: meet at 1

already met

a = [7]
  1. n = 1
  2. L=0, R=0 from the start

Result: meet at 0

even not yet

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

Result: not met

Try it

Write stopOnMeet(a). a is an array of integers. L is the left index, start 0. R is the right index, start n-1. After each inward step print L, R, and whether they met. Return nothing. On [4, 1, 9] they meet at 1. On [7] they start met. On [4, 1, 9, 1] they are not met after one close.

a is nonempty. Length ≥ 1.