Problem · Stack
Command Undo Data Structure
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.
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
01 · 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.
More Netflix problems
public String[] runCommandUndo(String[] operations) {
// write your code here
}
operations["ADD 5", "MUL 3", "UNDO", "PRINT"]
expected["5"]
checking account