Drill

ProblemsTypeScript › patterns

Replay a log that can take it back

mediumpatternsStacksParsingSimulationTypeScript

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

replayLog(commands: list<string>) → int

Solve it in the editor →

Where you start

function replayLog(commands: string[]): number {
  
}

Worked examples

CallResult
replayLog(["5","3","undo"])5
replayLog(["5","undo","undo"])0
replayLog(["10","-4","2"])8
replayLog([])0

Hint

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

Reference solution in TypeScript
function replayLog(commands: string[]): number {
  const applied: number[] = [];
  let total = 0;
  for (const command of commands) {
    if (command === "undo") {
      if (applied.length > 0) total -= applied.pop() as number;
    } else {
      const amount = parseInt(command, 10);
      applied.push(amount);
      total += amount;
    }
  }
  return total;
}

The same problem in another language

More patterns problems in TypeScript