Replay a log that can take it back
A stock adjustment screen records every change, and an undo command that cancels whichever change came last.
- A command is either a signed whole number to apply, or the word "undo".
- An undo cancels the most recent change that is still standing.
- An undo with nothing left to cancel does nothing.
- Start from zero and return the total once every command has run.
replay_log(commands: list<string>) → int
Where you start
def replay_log(commands: list[str]) -> int:
Worked examples
| Call | Result |
|---|---|
replay_log(["5", "3", "undo"]) | 5 |
replay_log(["5", "undo", "undo"]) | 0 |
replay_log(["10", "-4", "2"]) | 8 |
replay_log([]) | 0 |
Hint
Keep the applied changes on a stack. Undo pops the last one off and subtracts it back out.
Reference solution in Python
def replay_log(commands: list[str]) -> int:
applied = []
total = 0
for command in commands:
if command == "undo":
if applied:
total -= applied.pop()
else:
amount = int(command)
applied.append(amount)
total += amount
return total