Balance prefix for plus-minus walks
Updated
Treat the walk as +1 and −1. Inclusive P[i] = a[0]+…+a[i]. A plus-minus walk is balanced when every prefix is ≥ 0 and P[n-1]=0. A negative prefix is an unmatched minus.
What to focus on
This is the parenthesis-depth check on an array. P[i] is the height after index i, not a range undo.
Worked examples
balanced
a = [1, -1, 1, -1]- 1
- 1-1=0
- 0+1=1
- 1-1=0
- never < 0, last 0
Result: P = [1, 0, 1, 0] · valid
goes negative
a = [1, -1, -1, 1]- 1
- 0
- 0-1=-1
- then 0
- negative at i=2
Result: P = [1, 0, -1, 0] · invalid
one plus
a = [1]- P = [1]
- last is not 0
Result: invalid as a closed walk
Try it
Write balancePrefix(a). a is an array of +1 and −1. Inclusive P[i] is the running height after index i. Return P. Valid means every prefix ≥ 0 and last equals 0. [1, -1, 1, -1] → [1, 0, 1, 0] valid [1, -1, -1, 1] → invalid at the first negative [1] → invalid because last is not 0
a is a non-empty array of +1 and −1. P[i] covers a[0..i].