awelgorithms

Simulate interleaved stack operations

Updated

Interleaving means pushes and pops mixed, as in pushed some, popped some, pushed more. The stack at each moment is a single LIFO, not two structures.

What to focus on

One stack, one cursor through the input. Do not reset. A pop in the middle only sees what has been pushed so far.

Worked examples

mid pop

push 4, push 1, pop, push 9, pop, pop
  1. pop 1, pop 9, pop 4

Result: yields 1,9,4

nested like

push 4, push 1, push 9, pop, pop, push 8, pop, pop
  1. 9,1, then 8, then 4

Result: yields 9,1,8,4

partial bury

push 4, push 1, pop, push 9
  1. pop 1
  2. leave [4, 9]

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

Try it

Write simulate(ops). ops is the mixed sequence of push and pop. The stack starts empty. Print the pop log. It must stay LIFO. push 4, push 1, pop, push 9, pop, pop yields 1,9,4. The nested-like sequence yields 9,1,8,4. push 4, push 1, pop, push 9 leaves [4, 9].

The operation sequence never pops an empty stack. Values are integers.