KatInterview

Text Editor with Undo and Word Suggestions

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structurestrieundo-redo

Last 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() or redo() 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.