awelgorithms

Reconstruct remaining stack items

Updated

Given a push log and which values already popped, the remaining stack is the pushed values that have not popped, in push order, top = last unpopped.

What to focus on

If you only see the pop outputs, several stacks could have produced them. Remaining items are the pushes minus the pops, still in LIFO order.

Worked examples

some popped

a = [], push 4,1,9, pop, pop
  1. popped 9 then 1
  2. 4 remains

Result: [4]

none popped

a = [], push 4,1,9
  1. all remain
  2. top 9

Result: [4, 1, 9]

all popped

a = [], push 4,1, pop, pop
  1. empty

Result: []

Try it

Write remaining(a). a is the stack after the given pushes and pops, written [bottom, ..., top]. Return the unpopped values in push order. Top is the last unpopped value. After push 4,1,9 and two pops, remaining is [4]. After no pops, [4, 1, 9]. After popping everything, [].

The log never pops more than it pushed. Values are integers. Remaining may be empty.