Drill

ProblemsC# › patterns

Replay a log that can take it back

mediumpatternsStacksParsingSimulationC#

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

ReplayLog(commands: list<string>) → int

C# 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

public int ReplayLog(List<string> commands) {
    
}

Worked examples

CallResult
ReplayLog(new List<string> { "5", "3", "undo" })5
ReplayLog(new List<string> { "5", "undo", "undo" })0
ReplayLog(new List<string> { "10", "-4", "2" })8
ReplayLog(new List<string> { })0

Hint

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

Reference solution in C#
public int ReplayLog(List<string> commands) {
    var applied = new Stack<int>();
    int total = 0;
    foreach (var command in commands) {
        if (command == "undo") {
            if (applied.Count > 0) total -= applied.Pop();
        } else {
            int amount = int.Parse(command);
            applied.Push(amount);
            total += amount;
        }
    }
    return total;
}

The same problem in another language

More patterns problems in C#