Problem · Stack

Undo and Redo Command History

Learn this problem
MediumNetflix logoNetflixFULLTIMEONSITE INTERVIEW

Problem statement

Maintain an active command history while processing a sequence of operations.

Each row in operations has one of these forms:

  • ["EXECUTE", command]: append the nonempty, case-sensitive command identifier to the active history. Executing a new command clears every command currently available for redo.
  • ["UNDO"]: remove the most recently active command and make it available for redo. If the active history is empty, do nothing.
  • ["REDO"]: restore the most recently undone command to the end of the active history. If no command is available for redo, do nothing.

After every operation, encode the complete active history as one string. Join its command identifiers in application order with |. Encode an empty active history as the empty string.

Return the encoded snapshots in operation order.

Function

runUndoRedoHistory(operations: String[][]) → String[]

Examples

Example 1

operations = [["EXECUTE","build"],["EXECUTE","test"],["UNDO"],["REDO"]]return = ["build","build|test","build","build|test"]

The undo removes test from the active history, and redo restores that same command.

Example 2

operations = [["EXECUTE","a"],["EXECUTE","b"],["EXECUTE","c"],["UNDO"],["UNDO"],["EXECUTE","d"],["REDO"],["UNDO"]]return = ["a","a|b","a|b|c","a|b","a","a|d","a|d","a"]

After two undos, executing d clears the redo branch. The following redo is therefore a no-op, and the final undo removes d.

Example 3

operations = [["UNDO"],["REDO"],["EXECUTE","x"],["UNDO"],["UNDO"],["REDO"],["REDO"]]return = ["","","x","","","x","x"]

Undo and redo are no-ops when their corresponding history is empty. The command x can be restored only once.

Constraints

  • 1 <= operations.length <= 500
  • Each row is exactly ["UNDO"], ["REDO"], or ["EXECUTE", command].
  • 1 <= command.length <= 100.
  • Each command identifier contains only uppercase or lowercase ASCII letters, digits, underscores, or hyphens and is compared by exact, case-sensitive equality.
  • The total number of command identifiers across all returned snapshots is at most 125000.

More Netflix problems

drafts saved locally
public String[] runUndoRedoHistory(String[][] operations) {
    // write your code here
}
operations[["EXECUTE","build"],["EXECUTE","test"],["UNDO"],["REDO"]]
expected["build", "build|test", "build", "build|test"]
checking account