Problem · Design

Text Editor, Part 2: Undo and Redo

Learn this problem
MediumOpenAI logoOpenAIFULLTIMEPHONE SCREEN

Problem statement

Extend a text buffer with undo and redo history. The buffer begins empty.

Supported operations

Each operation is a string array:

  • ["INSERT", position, text]: insert text immediately before the character at the zero-based position.
  • ["DELETE", start, end]: delete the characters in the half-open range [start, end).
  • ["UNDO"]: undo the most recent insert or delete that is still applied.
  • ["REDO"]: reapply the most recently undone operation.
  • ["GET"]: append the complete current text to the output.

Every insert and delete must be undoable. Executing a new insert or delete after an undo clears the redo history. UNDO or REDO does nothing when its corresponding history is empty.

Interview sequence

  1. Part 1: Basic Text Buffer
  2. Part 2: Undo and Redo

Function

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

Examples

Example 1

operations = [["INSERT", "0", "hello"], ["INSERT", "5", "!"], ["DELETE", "1", "4"], ["GET"], ["UNDO"], ["GET"], ["REDO"], ["GET"], ["UNDO"], ["INSERT", "5", "?"], ["REDO"], ["GET"]]return = ["ho!", "hello!", "ho!", "hello?!"]

Undo restores the deleted substring and redo removes it again. After the second undo, inserting ? clears the redo history, so the following REDO has no effect.

More OpenAI problems

drafts saved locally
public String[] processTextEditorHistory(String[][] operations) {
  // write your code here
}
operations[["INSERT", "0", "hello"], ["INSERT", "5", "!"], ["DELETE", "1", "4"], ["GET"], ["UNDO"], ["GET"], ["REDO"], ["GET"], ["UNDO"], ["INSERT", "5", "?"], ["REDO"], ["GET"]]
expected["ho!", "hello!", "ho!", "hello?!"]
checking account