Drill

ProblemsPython › patterns

Replay a log that can take it back

mediumpatternsStacksParsingSimulationPython

A stock adjustment screen records every change, and an undo command that cancels whichever change came last.

replay_log(commands: list<string>) → int

Solve it in the editor →

Where you start

def replay_log(commands: list[str]) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More patterns problems in Python