Pop while the top loses
Updated
While the newcomer beats the top, pop. Stop when the top survives, the newcomer dies, they tie, or the stack is empty. Then maybe push the newcomer if it lived.
What to focus on
The test uses direction (must oppose) and magnitude. Same direction: do not pop. Empty stack: newcomer survives and is pushed.
Worked examples
chain
a = [8, 2, -5] wait 8,2 right, -5 left- -5 pops 2 (2<5)
- 8>5 so 8 stays, -5 dies
Result: [8]
newcomer wins all
a = [2, 3], incoming -10- pop 3, pop 2
- push -10
Result: [-10]
no oppose
a = [2, 3], incoming 4- same sign
- just push
Result: [2, 3, 4]
Try it
Write popWhileLoses(stack, incoming). stack is the survivor stack, bottom to top. incoming is a non-zero integer (positive right, negative left). Pop only while the top loses an opposing fight. Then push incoming if it still lives. Return the stack. a = [8, 2, -5] wait 8,2 right, -5 left → [8]. a = [2, 3], incoming -10 → [-10]. a = [2, 3], incoming 4 → [2, 3, 4].
The stack starts non-empty. Incoming is a non-zero integer. Positive right, negative left.