Command executor with undo
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Netflix's coding / problem solving round, last asked Apr 2026. It tests design patterns, stacks and data structure design.
Implement a command manager that executes commands against some state and can undo them. execute applies a command and records it; undo reverses the most recent command that has not been undone yet. Use a small key-value document as the state, with set and delete commands, and design it so new command types can be added.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
execute(command) -> Noneapplies the command to the state and pushes what is needed to reverse it. -
undo() -> boolreverses the latest executed command and returnsTrue, or returnsFalsewhen there is nothing to undo. -
state() -> dictreturns the current document. - Commands:
("set", key, value)and("delete", key); deleting a missing key is a no-op that still undoes cleanly.
Example
execute(("set", "a", 1))
execute(("set", "a", 2))
execute(("set", "b", 5))
execute(("delete", "a"))
state() -> {"b": 5}
undo() -> True; state() -> {"b": 5, "a": 2}
undo() -> True; state() -> {"a": 2}
undo() -> True; state() -> {"a": 1}
undo() -> True; state() -> {}
undo() -> False
Constraints
- Up to 10^5 commands;
executeandundoshould beO(1)apart from the cost of the command itself.
Clarifying questions
- Does each command know how to reverse itself, or does the manager store snapshots?
- Should undoing a no-op command be a separate step or skipped?
- Is redo needed, and what happens to the redo history after a new
execute? - Is there a limit on history length or memory?
What a strong answer covers
- The command pattern: each command records the inverse information it needs at execute time (the previous value and whether the key existed), so undo is exact.
- A stack of executed commands; inverse operations rather than full snapshots, and the memory trade-off between the two.
- Correct handling of "key did not exist before" versus "key held
None". - Tests for repeated sets on one key, delete of a missing key, and undo past the beginning.
Follow-ups
- Add
redo(), cleared by any newexecute. - Group several commands into one transaction that undoes in one step.
- Bound memory by keeping only the last N commands.
- Commands with side effects outside the state (sending an email): what can undo promise?
Where it's asked
- Netflix · Coding / problem solving · Last asked Apr 2026Live coding on under-specified requirements
What it tests
design patterns · stacks · data structure design
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
