awelgorithms

Leave the first valid top

Updated

After pop-while, either the stack is empty or peek() satisfies the condition. That remaining top is the nearest previous (or next, depending on scan direction) that passed. Do not pop it.

What to focus on

If you need to record an answer from that top, peek it. If you then push the current value, the new top is the current, and the valid one is buried again. That is intended.

Worked examples

kept

a = [1, 3, 5], after pop-while top>4
  1. 3 is valid
  2. leave it

Result: peek 3

empty leftover

a = [5, 6], after pop-while top>1
  1. no valid top

Result: []

then push

a = [1, 3], push 4
  1. 4 is new top
  2. 3 still under

Result: [1, 3, 4]

Try it

Write leftoverTop(a, pred). a is the stack, written [bottom, ..., top]. pred is a function that takes one value and returns true or false. After pop-while, peek the leftover top if any. Then you may push the current value. After pop-while on [1, 3, 5] vs pred = top > 4, peek 3. After draining [5, 6], leftover is empty. Then push the current value.

The stack starts non-empty. Values are integers. pred is a function that takes one value and returns true or false. Empty leftover after pop-while is a legal outcome.