Problem · Stack

Command Undo Data Structure

EasyNetflixFULLTIMEONSITE 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.

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
drafts saved locally
public String[] runCommandUndo(String[] operations) {
    // write your code here
}
operations["ADD 5", "MUL 3", "UNDO", "PRINT"]
expected["5"]
checking account