awelgorithms

Trace a sequence of pushes and pops

Updated

A trace is the stack after each operation, plus any popped values. Write the stack (bottom to top) every step so you can see LIFO instead of guessing.

What to focus on

Start at []. Apply ops left to right. The final stack plus the pop log is the whole story.

Worked examples

mixed

a = [], ops: push 4, push 1, pop, push 9
  1. [4] → [4,1] → pop 1 leave [4] → [4,9]

Result: stack [4, 9], popped [1]

drain

a = [4, 1, 9], pop, pop, pop
  1. 9,1,4
  2. []

Result: popped 9,1,4

nested like

a = [], push 4, push 1, push 9, pop, pop, push 8
  1. [4,1,9] → [4,1] → [4] → [4,8]

Result: stack [4, 8], popped [9, 1]

Try it

Write traceOps(a). a is the stack, written [bottom, ..., top]. Print the stack after each operation, plus popped values. From []: push 4, push 1, pop, push 9 leaves [4, 9] and popped [1]. Drain [4, 1, 9] pops 9,1,4. push 4,1,9, pop, pop, push 8 leaves [4, 8].

Every pop happens on a non-empty stack. Values are integers.