Building a Live Text Editor: Buffer, History, and Suggestions
Data Structure DesignModel answerLast 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 positiondelete(position, length)— removelengthcharacters starting at positionread(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 editredo()— 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
kmost 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to design layered data structures, manage reversible state, efficiently query ranked results, and reason about distributed concurrency.
Stage 1: Buffer Implementation
For small to moderate documents, a simple string or array suffices. Insert and delete are O(n) due to shifting characters, but the implementation is straightforward and correct.
For larger documents or heavy editing, consider:
- Gap buffer: maintains a movable gap where edits cluster, making local edits O(1) amortized
- Rope: a balanced tree of strings, making insert/delete O(log n)
- Piece table: tracks sequences of pieces pointing into original and append-only added text
Start simple unless the interviewer specifies performance requirements for large documents.
Validation: bounds-check all positions and lengths. Position must be 0 ≤ pos ≤ length for insert, and 0 ≤ pos < length and pos + len ≤ length for delete.
Stage 2: Undo and Redo
Use two stacks:
- Undo stack: stores each operation as it's performed
- Redo stack: stores operations that have been undone
Each operation record must contain enough information to reverse it:
- Insert(pos, text) reverses to Delete(pos, text.length)
- Delete(pos, length) reverses to Insert(pos, deleted_text)
When undo is called, pop from the undo stack, apply the inverse operation, and push the original operation onto the redo stack. When redo is called, pop from redo and push onto undo.
Critical: when a new edit happens after an undo, clear the redo stack entirely, since that future history is no longer valid.
Grouping edits: the basic implementation undoes one character at a time. To group consecutive inserts (typing a word) or deletes (backspacing), track time or operation type and merge adjacent operations into compound actions.
Stage 3: Autocomplete with Trie
Build a trie where:
- Each node represents a character
- Terminal nodes (word endings) store a frequency count
- Insert words as they're typed into the buffer
Top-k retrieval: traverse from the prefix to collect all descendant words with their frequencies, then select the k highest. With lexicographic tie-breaking, sort by (frequency descending, word ascending).
Optimization: for large vocabularies, precompute and cache the top-k list at each node during insertion. This trades memory and update cost (O(k) per insert) for O(k) query time instead of O(words_under_prefix).
Complexity:
- Insert word: O(word_length)
- Query without caching: O(prefix_length + total_chars_in_subtree + W log W) where W is the number of matching words
- Query with caching: O(prefix_length + k)
Stage 4: Concurrent Editing with Operational Transformation
OT ensures that when two clients apply the same set of operations in different orders, they reach the same final state.
System architecture:
- Central server receives operations from all clients, assigns a global sequence number, and broadcasts them
- Each client maintains a local document state and a revision number
- Operations are tagged with the revision they were created at
- When a client receives a remote operation, it transforms any in-flight local operations against it
Transformation rules:
For two concurrent operations A and B created at the same revision:
-
Insert vs Insert:
- If posA < posB: A unchanged, B.pos += A.length
- If posA > posB: A.pos += B.length, B unchanged
- If posA == posB: apply a tie-breaker (e.g., client ID) to ensure deterministic ordering
-
Insert vs Delete:
- Insert at pos, Delete at [delPos, delPos + delLen)
- If pos <= delPos: Delete.pos += Insert.length
- If pos > delPos + delLen: Insert.pos -= delLen
- If pos inside delete range: Insert.pos = delPos (or define a consistent rule)
-
Delete vs Delete:
- Overlapping ranges must shrink to avoid double-deletion
- If ranges don't overlap, adjust positions
- If they partially overlap, adjust length and position to reflect what remains
Convergence property: OT requires that transform(A, B) and transform(B, A) produce operations such that applying A then transform(B, A) yields the same result as applying B then transform(A, B). This is called the TP2 property and must be verified for correctness.
Undo in collaborative mode: local undo must transform the inverse operation against all remote edits that have arrived since the original edit, so the undo applies to the current state correctly.
Testing: generate random concurrent edit sequences and verify all clients converge to identical documents. Test edge cases like simultaneous inserts at position 0, overlapping deletes, and delete followed by insert at the same position.
Code Outline
class TextBuffer:
def __init__(self):
self.content = ""
self.undo_stack = []
self.redo_stack = []
def insert(self, pos, text):
if not (0 <= pos <= len(self.content)):
raise ValueError("Position out of bounds")
self.content = self.content[:pos] + text + self.content[pos:]
self.undo_stack.append(('insert', pos, text))
self.redo_stack.clear()
def delete(self, pos, length):
if not (0 <= pos < len(self.content) and pos + length <= len(self.content)):
raise ValueError("Invalid delete range")
deleted = self.content[pos:pos+length]
self.content = self.content[:pos] + self.content[pos+length:]
self.undo_stack.append(('delete', pos, deleted))
self.redo_stack.clear()
def read(self, pos, length):
return self.content[pos:pos+length]
def undo(self):
if not self.undo_stack:
return
op_type, pos, data = self.undo_stack.pop()
if op_type == 'insert':
length = len(data)
self.content = self.content[:pos] + self.content[pos+length:]
self.redo_stack.append(('insert', pos, data))
else: # delete
self.content = self.content[:pos] + data + self.content[pos:]
self.redo_stack.append(('delete', pos, data))
def redo(self):
if not self.redo_stack:
return
op_type, pos, data = self.redo_stack.pop()
if op_type == 'insert':
self.content = self.content[:pos] + data + self.content[pos:]
self.undo_stack.append(('insert', pos, data))
else:
length = len(data)
self.content = self.content[:pos] + self.content[pos+length:]
self.undo_stack.append(('delete', pos, data))
class TrieNode:
def __init__(self):
self.children = {}
self.frequency = 0
self.is_end = False
class Autocomplete:
def __init__(self):
self.root = TrieNode()
def add_word(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
node.frequency += 1
def get_top_k(self, prefix, k):
node = self.root
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
results = []
self._collect_words(node, prefix, results)
# Sort by frequency desc, then lexicographically
results.sort(key=lambda x: (-x[1], x[0]))
return [word for word, freq in results[:k]]
def _collect_words(self, node, current, results):
if node.is_end:
results.append((current, node.frequency))
for char, child in node.children.items():
self._collect_words(child, current + char, results)
class Operation:
def __init__(self, op_type, pos, data, revision, client_id):
self.type = op_type # 'insert' or 'delete'
self.pos = pos
self.data = data
self.revision = revision
self.client_id = client_id
def transform_insert_insert(op1, op2):
"""Transform two concurrent inserts"""
if op1.pos < op2.pos:
return op1, Operation('insert', op2.pos + len(op1.data), op2.data, op2.revision, op2.client_id)
elif op1.pos > op2.pos:
return Operation('insert', op1.pos + len(op2.data), op1.data, op1.revision, op1.client_id), op2
else:
# Tie-break by client_id
if op1.client_id < op2.client_id:
return op1, Operation('insert', op2.pos + len(op1.data), op2.data, op2.revision, op2.client_id)
else:
return Operation('insert', op1.pos + len(op2.data), op1.data, op1.revision, op1.client_id), op2
Complexity
- Buffer operations: O(n) for insert/delete with simple string, O(log n) with rope
- Undo/redo: O(operation cost)
- Autocomplete insert: O(word length)
- Autocomplete query: O(prefix length + matching words) without caching
- OT transformation: O(1) per operation pair
Common Mistakes
- Forgetting to clear the redo stack when a new edit occurs
- Not storing the deleted text in the undo record for delete operations
- Off-by-one errors in position validation
- Not handling the tie-break case when two inserts happen at the same position
- Assuming operations can be applied in any order without transformation
- Ignoring overlapping deletes in the OT rules