FrontendInterviews.dev

Loading problem…

53. Undo/Redo for Text Editor

Medium•
Acceptance: 76.19%
•
🔓3/3 Pro unlocks today

Implement a TextEditor class that supports INSERT, DELETE, UNDO, and REDO operations. The editor should maintain a history of operations using a stack-based approach.

Requirements

1. Basic Operations

  • INSERT(text, position): Insert text at a given position
  • DELETE(position, length): Delete characters starting at position
  • UNDO(): Undo the last operation
  • REDO(): Redo the last undone operation
  • getText(): Return the current text content

Example Usage

const editor = new TextEditor();

editor.insert('Hello', 0);        // text = 'Hello'
editor.insert(' World', 5);      // text = 'Hello World'
editor.delete(5, 6);              // text = 'Hello'
editor.undo();                    // text = 'Hello World'
editor.undo();                    // text = 'Hello'
editor.redo();                    // text = 'Hello World'

Key Concepts

  • Use two stacks: one for undo operations, one for redo operations
  • Store operations as objects with type and necessary data
  • When performing INSERT/DELETE, push to undo stack and clear redo stack
  • When UNDO, pop from undo stack, apply inverse operation, push to redo stack
  • When REDO, pop from redo stack, apply operation, push to undo stack

Constraints

  • Position must be valid (0 <= position <= text.length)
  • Delete length must be valid (position + length <= text.length)
  • UNDO should do nothing if no operations to undo
  • REDO should do nothing if no operations to redo
  • Operations should be reversible
  • Handle empty text and edge cases