awelgorithms

Expand is the only way the right edge moves

Updated

R increases only on expand (R += 1). Shrink moves L. A sliding-window pass never decrements R to undo an include.

What to focus on

R is monotonic non-decreasing. To drop a right cell you would need a different pattern (restart, or a new pass). Shrink leaves R where it is.

Worked examples

expand moves R

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

Result: R = 1

shrink leaves R

a = [4, 1, 9], L=0 R=2, shrink
  1. drop a[0]=4
  2. L += 1
  3. R stays 2

Result: R = 2

no R--

a = [4, 1, 9, 1], L=0 R=3
  1. R is already n-1
  2. shrinking still keeps R=3
  3. do not walk R left

Result: R stays 3

Try it

Write traceR(a). a is an array of integers. L is the left index. R is the right index. Expand is the only way R increases. Shrink leaves R. Print R after each move. It must never decrease. Return nothing. On [4, 1, 9] expand then shrink; [4, 1, 9, 1] shrink from (0, 3).

a is nonempty. The window starts non-empty (L ≤ R) except the first expand from R=-1.