Drill

ProblemsJava › patterns

Replay a log that can take it back

mediumpatternsStacksParsingSimulationJava

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

replayLog(commands: list<string>) → int

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int replayLog(List<String> commands) {
    
}

Worked examples

CallResult
replayLog(Main.<String>ls("5", "3", "undo"))5
replayLog(Main.<String>ls("5", "undo", "undo"))0
replayLog(Main.<String>ls("10", "-4", "2"))8
replayLog(Main.<String>ls())0

Hint

Keep the applied changes on a stack. Undo pops the last one off and subtracts it back out.

Reference solution in Java
int replayLog(List<String> commands) {
    Deque<Integer> applied = new ArrayDeque<>();
    int total = 0;
    for (String command : commands) {
        if (command.equals("undo")) {
            if (!applied.isEmpty()) total -= applied.pop();
        } else {
            int amount = Integer.parseInt(command);
            applied.push(amount);
            total += amount;
        }
    }
    return total;
}

The same problem in another language

More patterns problems in Java