FastPrepFastPrep
Problem Brief

Command Undo Data Structure

FULLTIMEONSITE INTERVIEW

Design a command system that mutates a state and supports undo. Redo is optional.

For this problem, the state is a single integer that starts at 0. Supported commands are:

  • ADD x: add x to the state
  • MUL x: multiply the state by x
  • UNDO: undo the most recent command that has not already been undone
  • PRINT: output the current state

Return the output lines produced by the command batch.

Function Description

Complete the function runCommandUndo in the editor below.

runCommandUndo has the following parameter:

  1. String[] operations: the commands to execute in order

Returns

String[]: the lines printed by PRINT operations.

1Example 1

Input
operations = ["ADD 5", "MUL 3", "UNDO", "PRINT"]
Output
["5"]
Explanation

After adding 5 and multiplying by 3, the state becomes 15. Undo reverts the multiplication, so PRINT outputs 5.

Constraints

Limits and guarantees your solution can rely on.

  • Each undo should revert exactly one previously executed mutating command.
  • Explain or implement the command history so that undo stays efficient.
public String[] runCommandUndo(String[] operations) {
    // write your code here
}
Input

operations

["ADD 5", "MUL 3", "UNDO", "PRINT"]

Output

["5"]

Sign in to submit your solution.