awelgorithms

Treat pop as undo of push

Updated

If the only mutation was push(x), pop undoes it and restores the previous stack. That is why editors, backtracking, and browsers use a stack for undo. Redo is a second stack of popped values (the next skill family).

What to focus on

Undo is not set to empty. It peels one action. Two pushes need two undos.

Worked examples

one undo

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

Result: [4, 1]

two undos

a = [4, 1, 9], undo undo
  1. pop 9 then 1

Result: [4]

undo after push

a = [4, 1], push 9, undo
  1. back to [4, 1]

Result: [4, 1]

Try it

Write undo(a). a is the stack, written [bottom, ..., top]. Undo means pop. Each undo is one pop, not a reset. From [4, 1, 9], undo once → [4, 1]. Undo twice → [4]. Undo after push 9 onto [4, 1] → [4, 1].

The stack is non-empty before each undo. Values are integers. Undo means pop.