progress

~/problems / Stacks / Stacks

An undo log with a stack

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~12 min

A tiny editor starts empty. Write run_editor(commands: list[str]) -> str that applies the commands and returns the final text:

  • "type <word>" appends word (lowercase letters).
  • "delete <k>" removes the last k characters (or all, if fewer).
  • "undo" cancels the most recent type or delete not yet undone; with nothing to undo it does nothing. There's no redo.
run_editor(["type abc", "type de", "undo"])                        # "abc"
run_editor(["type hello", "delete 2", "type p", "undo", "undo"])   # "hello"
#  "hello" -> "hel" -> "help" -> undo the type: "hel" -> undo the delete: "hello"
run_editor(["type ab", "delete 5", "undo"])                        # "ab"
run_editor(["undo", "type x"])                                     # "x"

Up to 2 * 10^5 commands, typed letters and deleted characters. ⭐ Bonus: a speed test earns a star for work proportional to the input (no full copy of the text per edit).

Show hint

push onto a stack just what reverses each edit: a count for type, the removed letters for delete. Keep the text as a list of characters.

Topic: Stacks. Matching pairs, undo history and evaluating expressions with a stack.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc