awelgorithms

Place same-direction pointers

Updated

Same-direction placement puts both indices on the left and lets R, the lead, run ahead of L, the trail. They travel the same way, not toward each other.

What to focus on

After placement, 0 ≤ L ≤ R < n. The lead never starts behind the trail. They may start together or with R already one step ahead.

Worked examples

together

a = [4, 1, 9]
  1. L ← 0
  2. R ← 0
  3. gap 0 until the lead moves

Result: L=0, R=0

lead ahead

a = [4, 1, 9]
  1. L ← 0
  2. R ← 1
  3. R already leads by 1

Result: L=0, R=1

empty

a = []
  1. n = 0
  2. do not invent L or R

Result: no L, R

Try it

Write placeSameDir(a). a is an array of integers. L is the trail index. R is the lead index. Set both on the left when n ≥ 1. On empty, print that there is no L or R. On [4, 1, 9] print L=0, R=0 then L=0, R=1. On [] print no L, R.

a may be empty. When nonempty, length ≥ 1.