Problem · Stack
Command Undo Data Structure
Learn this problemProblem statement
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: addxto the stateMUL x: multiply the state byxUNDO: undo the most recent command that has not already been undonePRINT: output the current state
Return the output lines produced by the command batch.
Function
runCommandUndo(operations: String[]) → String[]Complete the function runCommandUndo in the editor below.
runCommandUndo has the following parameter:
String[] operations: the commands to execute in order
Returns
String[]: the lines printed by PRINT operations.
Examples
Example 1
operations = ["ADD 5", "MUL 3", "UNDO", "PRINT"]return = ["5"]After adding 5 and multiplying by 3, the state becomes 15. Undo reverts the multiplication, so PRINT outputs 5.
Constraints
- Each undo should revert exactly one previously executed mutating command.
- Explain or implement the command history so that undo stays efficient.