Design command executor with undo
Company: Netflix
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of the command pattern, state and history management, failure handling, and appropriate data structure use for implementing undo semantics, measuring the ability to design clear abstractions that maintain correct system state.
Constraints
- 0 <= len(operations) <= 200000
- Each numeric value x is an integer in the range [-10^9, 10^9]
- Every command is one of ('ADD', x), ('MUL', x), ('DIV', x), ('SET', x), or ('UNDO',)
- The counter value after every successful command fits in a signed 64-bit integer
Examples
Input: ([],)
Expected Output: 0
Explanation: No commands are executed, so the counter remains at its initial value 0.
Input: ([('ADD', 5), ('MUL', 3), ('UNDO',), ('UNDO',)],)
Expected Output: 0
Explanation: 0 -> 5 -> 15 -> undo to 5 -> undo to 0.
Input: ([('UNDO',), ('ADD', 2), ('UNDO',), ('UNDO',)],)
Expected Output: 0
Explanation: The first and last UNDO do nothing because history is empty. The ADD 2 is undone by the middle UNDO.
Input: ([('ADD', 10), ('DIV', 0), ('UNDO',)],)
Expected Output: 0
Explanation: DIV by 0 fails, so it is not recorded. UNDO removes the earlier successful ADD 10 and restores the counter to 0.
Input: ([('ADD', 7), ('DIV', 2), ('MUL', 4), ('UNDO',)],)
Expected Output: 7
Explanation: DIV 2 fails because 7 is not evenly divisible by 2. Then MUL 4 makes the counter 28, and UNDO restores it to 7.
Input: ([('SET', 4), ('ADD', -6), ('MUL', -2), ('UNDO',), ('UNDO',)],)
Expected Output: 4
Explanation: 0 -> 4 -> -2 -> 4 -> undo to -2 -> undo to 4.
Input: ([('ADD', 3), ('MUL', 0), ('ADD', 5), ('UNDO',), ('UNDO',), ('UNDO',)],)
Expected Output: 0
Explanation: 0 -> 3 -> 0 -> 5 -> undo to 0 -> undo to 3 -> undo to 0. This shows why storing previous states works well for undo.
Hints
- Use a stack to remember enough information to undo the last successful command.
- For this counter-based version, storing the previous counter value before each successful command makes every undo operation simple, even for commands like MUL 0 or SET.