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.
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.
Where you start
public int ReplayLog(List<string> commands) {
}
Worked examples
| Call | Result |
|---|---|
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;
}