KatInterview

Building a Live Text Editor: Buffer, History, and Suggestions

Data Structure DesignModel answer
HardModel answerData Structure Designdata-structuresundo-redotrie

Last updated

Design and implement a text editor with insert/delete operations, undo/redo history, prefix-based autocomplete with frequency ranking, and multi-user concurrent editing.

You're building the core engine of a text editor. Implement it in four progressive stages, where each stage adds new functionality to the previous one. Design your interfaces to be extensible from the start.

Stage 1: Basic Text Buffer

Create a text buffer that supports:

  • insert(position, text) — insert text at the given position
  • delete(position, length) — remove length characters starting at position
  • read(position, length) — return the substring at that range

Positions are zero-indexed character offsets. Handle boundary conditions appropriately.

Stage 2: History Management

Add undo and redo capabilities:

  • undo() — reverse the most recent edit
  • redo() — reapply an edit that was undone

Each insert or delete is a separate undoable action. Once a new edit is made after undoing, the forward history should be discarded.

Stage 3: Word Completion

Implement autocomplete with frequency-based ranking:

  • Track all words typed into the buffer
  • Given a prefix, return the top k most frequently used words that start with that prefix
  • Use lexicographic order to break ties

Use a trie structure for efficient prefix queries.

Stage 4: Concurrent Editing

Enable multiple users to edit the same document simultaneously. When two users make edits at the same time, their changes must be reconciled so all users converge to the same final document state.

Design a solution using operational transformation that handles:

  • Concurrent inserts at overlapping positions
  • Concurrent deletes affecting the same range
  • The interaction between local edits and remote changes

Explain your transformation rules, system architecture, and how you ensure convergence.

Hints

Hint 1

For the buffer, consider whether a simple string works for small documents or if you need a gap buffer or rope for efficiency.

Hint 2

The undo stack stores inverse operations; what happens to the redo stack when a new edit occurs after an undo?

Hint 3

In the trie, you can store word counts at terminal nodes and either compute top-k on demand or cache results at each node.

Hint 4

For operational transformation, define how insert and delete operations adjust each other's positions when applied in different orders.