Text Editor with Undo and Word Suggestions
Data Structure DesignModel answerLast updated
Build a text editor class supporting character insertion, deletion, cursor movement, undo/redo operations, and prefix-based word autocompletion.
You need to implement a TextEditor class that manages a text buffer with editing capabilities and intelligent word suggestions.
Your editor must support these operations:
insert(char): Add a character where the cursor is currently positioned, then advance the cursor by one position.delete(): Remove the character immediately before the cursor (backspace behavior).move_cursor(position): Relocate the cursor to a specified index in the text.undo(): Reverse the most recent edit (either an insertion or deletion).redo(): Reapply the most recently undone edit.suggest(prefix): Return up to 3 words that begin with the given prefix, ranked by how frequently they've been typed. Words are alphanumeric sequences separated by whitespace.
Requirements
- Insertion and deletion must run faster than O(N) where N is the current text length.
- The text will contain at most 10^5 characters.
- Word frequency counts are incremented when a space or newline character is inserted immediately after an alphanumeric sequence.
- For
suggest, return words sorted by frequency (highest first), with alphabetical ordering breaking ties.
Behavior Details
- Cursor positions range from 0 to the text length (inclusive). Position 0 is before the first character.
- Attempting to delete when the cursor is at position 0 does nothing.
- Calling
undo()orredo()when no operations are available does nothing. - Any new edit operation clears all redo history.
- Word counting is cumulative across the editing session; undo operations do not decrement word counts.
Example Usage
editor = TextEditor()
editor.insert('c')
editor.insert('a')
editor.insert('t')
# Buffer now contains "cat", cursor at position 3
editor.delete()
# Buffer now contains "ca", cursor at position 2
editor.undo()
# Buffer restored to "cat", cursor at position 3
editor.insert(' ')
# Word "cat" is now recorded with frequency 1
editor.suggest('c')
# Returns ['cat'] assuming it's the only word starting with 'c'
Edge Cases to Consider
- Deleting when the buffer is empty or cursor is at the start
- Undo/redo when stacks are empty
- Moving cursor beyond valid range (should clamp to valid positions)
- Committing words when multiple spaces are typed consecutively
- Prefix matching when no words exist in the dictionary
Hints
Hint 1
Consider using two stacks to represent text before and after the cursor for O(1) insertion and deletion.
Hint 2
Store edit operations as commands rather than full text snapshots to keep undo/redo memory-efficient.
Hint 3
A trie structure can maintain precomputed top-k results at each node to accelerate prefix queries.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires three independent mechanisms working together: efficient text manipulation, reversible edit history, and fast prefix-based retrieval.
1. Text Buffer: Gap Buffer with Two Stacks
The core insight is representing the text as two stacks rather than a single contiguous array:
- Left stack: holds all characters before the cursor, in normal order
- Right stack: holds all characters after the cursor, in reverse order
With this representation:
insert(ch)becomesleft.append(ch)— O(1)delete()becomesleft.pop()— O(1)move_cursor(pos)transfers characters between stacks — O(|distance moved|)
The complete text is left + reversed(right), and the cursor position equals len(left).
For most editing workflows where consecutive edits happen near each other, cursor movement is minimal. Only large jumps across the document incur O(N) cost.
Alternative consideration: A rope (balanced tree of string chunks) provides O(log N) for all operations but is significantly more complex to implement correctly in an interview setting.
2. Edit History: Command Pattern
Rather than storing full text snapshots (which would be O(N) space per edit), store lightweight command records:
Each history entry contains (operation_type, cursor_position_before, character).
To undo:
- For an insert: move cursor to
pos + 1, then pop from left stack - For a delete: move cursor to
pos - 1, then pushcharacterto left stack
When a new edit occurs, the redo stack is cleared. This ensures that the timeline remains linear — you cannot redo an operation that existed in an alternate branch of history.
Why cursor position matters: The same character deleted at different positions produces different results when undone. Recording the position ensures we restore exactly the right state.
3. Autocomplete: Trie with Cached Top-K
A standard trie stores word frequencies, but querying requires traversing the entire subtree below a prefix node — potentially expensive.
Optimization: maintain a cached "top 3 words" list at every trie node.
When a word is committed (space or newline typed after alphanumeric characters):
- Increment its frequency count in a global dictionary
- Walk the trie path for that word
- At each node along the path, update its top-3 list
Updating a top-3 list:
- If the word already exists in the list, update its count
- Otherwise, add it to the list
- Sort by count (descending), then lexicographically
- Keep only the top 3 entries
Why this works: Word counts only increase, never decrease. When a word's count increases, it cannot fall out of any node's top-k unless k other words have higher counts. By updating every node on the path, we ensure no cached list becomes stale.
Query time: suggest(prefix) walks down the trie following the prefix (O(P) where P is prefix length), then returns the cached list at the terminal node — no subtree traversal needed.
Complexity Analysis
| Operation | Time Complexity | Space |
|---|---|---|
| insert | O(1) amortized, plus O(L) on word commit where L is word length | O(1) |
| delete | O(1) | O(1) |
| move_cursor | O(D) where D is distance moved | O(1) |
| undo / redo | O(D) where D is cursor movement needed | O(1) |
| suggest | O(P) where P is prefix length | O(1) |
Overall space: O(N + H + W) where N is text length, H is history depth, and W is total characters across all unique words ever committed.
Common Mistakes
- Using a single array for the buffer: Makes insertion O(N) due to shifting elements
- Storing full snapshots: Violates space constraints; history becomes O(N×H)
- Not clearing redo stack on new edits: Leads to inconsistent state when branching occurs
- Running DFS for every suggest query: Defeats the purpose of using a trie for fast retrieval
- Forgetting to handle edge cases: Empty buffer deletes, out-of-range cursor moves, empty stacks for undo/redo
Implementation
class TrieNode:
def __init__(self):
self.children = {}
self.top_words = [] # List of [word, frequency] pairs
class TextEditor:
def __init__(self):
# Gap buffer: two stacks
self.before_cursor = []
self.after_cursor = []
# History tracking
self.undo_history = []
self.redo_history = []
# Autocomplete
self.word_frequencies = {}
self.trie_root = TrieNode()
def insert(self, char):
cursor_pos = len(self.before_cursor)
self.before_cursor.append(char)
self.undo_history.append(('insert', cursor_pos, char))
self.redo_history.clear()
# Check if we just completed a word
if char in (' ', '\n'):
self._commit_current_word(cursor_pos)
def delete(self):
if not self.before_cursor:
return
cursor_pos = len(self.before_cursor)
char = self.before_cursor.pop()
self.undo_history.append(('delete', cursor_pos, char))
self.redo_history.clear()
def move_cursor(self, position):
# Clamp to valid range
position = max(0, min(position, len(self.before_cursor) + len(self.after_cursor)))
# Move characters between stacks
while len(self.before_cursor) > position:
self.after_cursor.append(self.before_cursor.pop())
while len(self.before_cursor) < position:
self.before_cursor.append(self.after_cursor.pop())
def undo(self):
if not self.undo_history:
return
op_type, cursor_pos, char = self.undo_history.pop()
if op_type == 'insert':
# Reverse an insertion: move to where char was inserted, then delete
self.move_cursor(cursor_pos + 1)
self.before_cursor.pop()
else: # delete
# Reverse a deletion: move to where char was, then insert it back
self.move_cursor(cursor_pos - 1)
self.before_cursor.append(char)
self.redo_history.append((op_type, cursor_pos, char))
def redo(self):
if not self.redo_history:
return
op_type, cursor_pos, char = self.redo_history.pop()
self.move_cursor(cursor_pos)
if op_type == 'insert':
self.before_cursor.append(char)
else: # delete
self.before_cursor.pop()
self.undo_history.append((op_type, cursor_pos, char))
def _commit_current_word(self, space_position):
# Find the alphanumeric sequence immediately before the space
end = space_position
start = end - 1
while start >= 0 and self.before_cursor[start].isalnum():
start -= 1
start += 1
if start < end:
word = ''.join(self.before_cursor[start:end])
self._add_word_to_trie(word)
def _add_word_to_trie(self, word):
# Update frequency
new_count = self.word_frequencies.get(word, 0) + 1
self.word_frequencies[word] = new_count
# Update trie path
node = self.trie_root
self._update_node_top_list(node, word, new_count)
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
self._update_node_top_list(node, word, new_count)
def _update_node_top_list(self, node, word, count):
# Find if word already in top list
found = False
for entry in node.top_words:
if entry[0] == word:
entry[1] = count
found = True
break
if not found:
node.top_words.append([word, count])
# Sort: first by frequency descending, then lexicographically
node.top_words.sort(key=lambda x: (-x[1], x[0]))
# Keep only top 3
node.top_words = node.top_words[:3]
def suggest(self, prefix):
node = self.trie_root
# Navigate to prefix node
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
# Return cached top words
return [word for word, _ in node.top_words]
This solution efficiently handles all requirements while maintaining clarity and correctness across edge cases.