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

int replayLog(std::vector<std::string> commands) {
    
}

Worked examples

CallResult
replayLog(std::vector<std::string>{std::string("5"), std::string("3"), std::string("undo")})5
replayLog(std::vector<std::string>{std::string("5"), std::string("undo"), std::string("undo")})0
replayLog(std::vector<std::string>{std::string("10"), std::string("-4"), std::string("2")})8
replayLog(std::vector<std::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++
int replayLog(std::vector<std::string> commands) {
    std::vector<int> applied;
    int total = 0;
    for (const std::string& command : commands) {
        if (command == "undo") {
            if (!applied.empty()) {
                total -= applied.back();
                applied.pop_back();
            }
        } else {
            int amount = std::stoi(command);
            applied.push_back(amount);
            total += amount;
        }
    }
    return total;
}

The same problem in another language

More patterns problems in C++