awelgorithms

Empty the stack with pop-while

Updated

If every remaining top fails, pop-while drains the stack. That is a legal outcome, not a crash. The caller then treats no candidate (sentinel, skip, or empty-stack branch).

What to focus on

Do not special-case drain vs one pop unless answers differ. The loop already covers drain.

Worked examples

drain

a = [9, 8, 7], pop while top > 1
  1. all fail

Result: []

stop early

a = [1, 8, 7], pop while top > 3
  1. 7 pop, 8 pop, 1 stays

Result: [1]

one left

a = [2, 9], pop while top > 5
  1. 9 pop
  2. 2 stays

Result: [2]

Try it

Write popWhile(a, pred). a is the stack, written [bottom, ..., top]. pred is a function that takes one value and returns true or false. The loop may drain the stack. That is allowed. Drain [9, 8, 7] with pred = top > 1 → []. Stop on [1, 8, 7] with pred = top > 3 leaving [1]. Stop on [2, 9] with pred = top > 5 leaving [2].

The stack starts non-empty. Values are integers. pred is a function that takes one value and returns true or false. The loop may drain the stack. That is this skill.