awelgorithms

Grow the window by moving right

Updated

Expand is R += 1. L stays. The new window is a[L..R] with the new R.

What to focus on

Only R moves. Require R+1 < n before the increment. Growing does not drop anything on the left.

Worked examples

from empty

a = [4, 1, 9], L=0 R=-1
  1. R += 1 → 0
  2. L stays 0

Result: L=0 R=0 · [4]

grow again

a = [4, 1, 9], L=0 R=0
  1. R += 1 → 1
  2. window now covers 0,1

Result: L=0 R=1 · [4, 1]

cannot grow

a = [7], L=0 R=0
  1. R+1 = 1 is not < n=1
  2. R stays 0

Result: stuck at R=0

Try it

Write grow(a, L, R). a is an array of integers. L is the left index and stays. R is the right index. Grow is R += 1 when R+1 < n. The window then includes the new a[R]. Print (L, R) after each grow. Return nothing. On [4, 1, 9] from (0, -1) then (0, 0) then (0, 1).

a is nonempty. R+1 < n at the start of each grow.