Drill

ProblemsGo › patterns

Replay a log that can take it back

mediumpatternsStacksParsingSimulationGo

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

replayLog(commands: list<string>) → int

Go 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

func replayLog(commands []string) int {
	
}

Worked examples

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

Hint

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

Reference solution in Go
func replayLog(commands []string) int {
	applied := []int{}
	total := 0
	for _, command := range commands {
	    if command == "undo" {
	        if len(applied) > 0 {
	            total -= applied[len(applied)-1]
	            applied = applied[:len(applied)-1]
	        }
	    } else {
	        amount, _ := strconv.Atoi(command)
	        applied = append(applied, amount)
	        total += amount
	    }
	}
	return total
}

The same problem in another language

More patterns problems in Go