awelgorithms

Push several values in order

Updated

A sequence of pushes is LIFO in reverse: the last push is the first future pop. Order of the pushes is the order of the buried values, bottom to top.

What to focus on

Push 4 then 1 then 9. Stack is [4, 1, 9]. Do not push them as a block that preserves array order on pop. Pop order will be 9,1,4.

Worked examples

three pushes

a = [], push 4, 1, 9
  1. after 4: [4]
  2. after 1: [4, 1]
  3. after 9: [4, 1, 9]

Result: [4, 1, 9]

two then one

a = [4, 1], push 9
  1. same end state

Result: [4, 1, 9]

then another

a = [4, 1, 9], push 8
  1. 8 is the new top

Result: [4, 1, 9, 8]

Try it

Write pushMany(a). a is the stack, written [bottom, ..., top]. Push 4, then 1, then 9 from [], printing the stack after each. Then push 9 onto [4, 1] and 8 onto [4, 1, 9]. The last printed top must be 8. [] → [4] → [4, 1] → [4, 1, 9]. Then [4, 1, 9] and [4, 1, 9, 8].

You start from [] or a prefix already pushed. You never pop. Values are integers.