15% off all plans & roadmaps Use code
See plansEditorial
Core insight
Design a Text Editor · Design Patterns
Core Insight for Design a Text Editor
The key intuition is to realize that all operations—typing, deleting, and moving—happen relative to the cursor. The cursor acts as a split point.
Instead of maintaining one monolithic string, we can split the text into two collections:
- Left Collection: Characters strictly to the left of the cursor.
- Right Collection: Characters strictly to the right of the cursor.
By using two stacks (or deques/lists), we can perform operations at the "top" of these stacks in or time.
- Typing: Pushes characters onto the
Leftstack. - Backspace: Pops characters from the
Leftstack. - Left Arrow: Pops from
Leftand pushes ontoRight. - Right Arrow: Pops from
Rightand pushes ontoLeft.
Invariant: The concatenation of Left and Reverse(Right) always represents the full text. The top of the Left stack is the character immediately left of the cursor; the top of the Right stack is the character immediately right of the cursor.
Visual Description: Imagine two stacks of plates facing each other. The cursor is the empty space between them.
- When you type "A", you place a plate "A" on the left stack.
- When you move left, you take the top plate from the left stack and place it on the right stack.
- When you move right, you take the top plate from the right stack and place it on the left stack.
- This ensures that we only ever touch the characters immediately adjacent to the cursor, avoiding the need to shift the entire "pile" of text.
Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 2296: Design a Text Editor Solution & Explanation
Problem Overview
TL;DR: The optimal solution treats the cursor as a boundary between two stacks (or a split buffer), allowing insertion, deletion, and movement operations rather than shifting the entire string.
In LeetCode 2296, "Design a Text Editor," we are tasked with building a class that simulates a standard text editor. The editor maintains a body of text and a cursor position. We must support adding text at the cursor, deleting text via backspace behavior, and moving the cursor left or right. Crucially, after moving the cursor, the system must return a "window" of up to 10 characters immediately to the left of the new cursor position.
This problem is a popular interview question because it tests the ability to choose a data structure that optimizes for localized modifications rather than global traversal.
Brute Force Approach for Design a Text Editor
The naive approach is to store the entire text in a single string (or dynamic array) and maintain an integer index representing the cursor's position.
- Add Text: Use string insertion at the cursor index. This requires shifting all characters after the cursor to the right.
- Delete Text: Remove characters at the index. This requires shifting all subsequent characters to the left.
- Move Cursor: Simply update the integer index.
- Return Window: Substring the text from
max(0, cursor - 10)tocursor.
1# Pseudo-code for Naive Approach
2class TextEditor:
3 def __init__(self):
4 self.text = ""
5 self.cursor = 0
6
7 def addText(self, text):
8 # String concatenation/slicing is O(N)
9 self.text = self.text[:self.cursor] + text + self.text[self.cursor:]
10 self.cursor += len(text)Why it fails: The time complexity for insertion and deletion in a standard string or array is , where is the total length of the text. With up to operations and text length potentially growing large, an operation inside the simulation loop results in a total complexity of (or ). This leads to a Time Limit Exceeded (TLE) error. We need an approach where operation costs depend on the input size (the length of text added/deleted/moved), not the total text length .
Algorithm Strategy: Design Patterns
We will implement the Two Stacks strategy. While a Doubly Linked List also works, Two Stacks is often more cache-friendly and easier to implement using dynamic arrays (like std::vector in C++, StringBuilder in Java, or list in Python).
Data Structures:
left_stack: Stores the text before the cursor.right_stack: Stores the text after the cursor. Crucially, we store theright_stackin reverse order. This means the character immediately to the right of the cursor is at the end (top) ofright_stack. This allows push/pop from the end.
Operations:
- addText(text): Iterate through
textand push every character ontoleft_stack. - deleteText(k): Pop up to characters from
left_stack. Return the actual count deleted. - cursorLeft(k): Move up to characters from the top of
left_stackto the top ofright_stack. - cursorRight(k): Move up to characters from the top of
right_stackto the top ofleft_stack. - Retrieving the Window: To return the last 10 characters, we simply look at the last 10 elements of
left_stack.
Execution Flow
Let's trace the operations with an example.
Initial State: left = [], right = [] (Cursor is at |)
-
addText("abc"):- Push 'a', 'b', 'c' to
left. - State:
left = ['a', 'b', 'c'],right = [] - Text:
abc|
- Push 'a', 'b', 'c' to
-
cursorLeft(2):- Pop 'c' from
left, push toright. - Pop 'b' from
left, push toright. - State:
left = ['a'],right = ['c', 'b'](Note:rightstores reverse suffix) - Text:
a|bc - Return last 10 of
left:"a"
- Pop 'c' from
-
deleteText(1):- Pop 'a' from
left. - State:
left = [],right = ['c', 'b'] - Text:
|bc
- Pop 'a' from
-
cursorRight(1):- Pop 'b' from
right, push toleft. - State:
left = ['b'],right = ['c'] - Text:
b|c - Return last 10 of
left:"b"
- Pop 'b' from
Proof of Correctness
The algorithm is correct because it maintains the structural invariant that the sequence left_stack concatenated with reversed(right_stack) is identical to the document text.
- Insertion: Adding to the end of
left_stackcorrectly places characters before the conceptual cursor. - Deletion: Removing from the end of
left_stackcorrectly removes characters immediately before the cursor. - Movement: Transferring elements between the tops of the two stacks simulates the cursor traversing the text without losing or reordering characters, as the
right_stackacts as a LIFO buffer for the text to the right.
Since we only manipulate the ends of the arrays/stacks, we avoid the shift penalty.
Pattern Reuse Notes
The "Design" pattern, specifically optimizing data structures for specific operations, is used in several high-frequency interview questions:
- LeetCode 146: LRU Cache - Uses a Doubly Linked List + Hash Map to optimize access and removal to .
- LeetCode 155: Min Stack - Uses an auxiliary stack to track the minimum value in .
- LeetCode 225: Implement Stack using Queues - Manipulates data structure constraints to mimic LIFO behavior.
- LeetCode 232: Implement Queue using Stacks - Uses two stacks to invert order, achieving FIFO behavior with amortized operations.
In all these problems, the core task is to combine or restrict standard data structures to satisfy strict complexity requirements.
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 2296
1class TextEditor {
2private:
3 // left represents text to the left of cursor
4 // right represents text to the right of cursor (stored in reverse)
5 string left;
6 string right;
7
8public:
9 TextEditor() {
10 // Initialize empty strings
11 }
12
13 void addText(string text) {
14 // Append text directly to the left stack
15 left += text;
16 }
17
18 int deleteText(int k) {
19 int count = 0;
20 // Remove up to k characters from the left stack
21 while (k > 0 && !left.empty()) {
22 left.pop_back();
23 k--;
24 count++;
25 }
26 return count;
27 }
28
29 string cursorLeft(int k) {
30 // Move k characters from left to right
31 while (k > 0 && !left.empty()) {
32 right.push_back(left.back());
33 left.pop_back();
34 k--;
35 }
36 return getLeftWindow();
37 }
38
39 string cursorRight(int k) {
40 // Move k characters from right to left
41 while (k > 0 && !right.empty()) {
42 left.push_back(right.back());
43 right.pop_back();
44 k--;
45 }
46 return getLeftWindow();
47 }
48
49 // Helper to get the last min(10, len) characters
50 string getLeftWindow() {
51 if (left.length() <= 10) {
52 return left;
53 }
54 return left.substr(left.length() - 10);
55 }
56};Java Solution for LeetCode 2296
1class TextEditor {
2 // StringBuilder acts as a dynamic array/stack
3 private StringBuilder left;
4 private StringBuilder right;
5
6 public TextEditor() {
7 left = new StringBuilder();
8 right = new StringBuilder();
9 }
10
11 public void addText(String text) {
12 left.append(text);
13 }
14
15 public int deleteText(int k) {
16 int count = 0;
17 // Delete up to k characters from the end of 'left'
18 int len = left.length();
19 int deleteCount = Math.min(len, k);
20 left.setLength(len - deleteCount);
21 return deleteCount;
22 }
23
24 public String cursorLeft(int k) {
25 // Move chars from left to right
26 int moveCount = Math.min(left.length(), k);
27 for (int i = 0; i < moveCount; i++) {
28 char c = left.charAt(left.length() - 1);
29 left.setLength(left.length() - 1);
30 right.append(c);
31 }
32 return getLeftWindow();
33 }
34
35 public String cursorRight(int k) {
36 // Move chars from right to left
37 int moveCount = Math.min(right.length(), k);
38 for (int i = 0; i < moveCount; i++) {
39 char c = right.charAt(right.length() - 1);
40 right.setLength(right.length() - 1);
41 left.append(c);
42 }
43 return getLeftWindow();
44 }
45
46 private String getLeftWindow() {
47 int len = left.length();
48 if (len <= 10) return left.toString();
49 return left.substring(len - 10);
50 }
51}Python Solution for LeetCode 2296
1class TextEditor:
2
3 def __init__(self):
4 # left stack stores characters to the left of cursor
5 # right stack stores characters to the right (reversed)
6 self.left = []
7 self.right = []
8
9 def addText(self, text: str) -> None:
10 for char in text:
11 self.left.append(char)
12
13 def deleteText(self, k: int) -> int:
14 count = 0
15 while k > 0 and self.left:
16 self.left.pop()
17 count += 1
18 k -= 1
19 return count
20
21 def cursorLeft(self, k: int) -> str:
22 while k > 0 and self.left:
23 self.right.append(self.left.pop())
24 k -= 1
25 return self._get_window()
26
27 def cursorRight(self, k: int) -> str:
28 while k > 0 and self.right:
29 self.left.append(self.right.pop())
30 k -= 1
31 return self._get_window()
32
33 def _get_window(self) -> str:
34 # Return last min(10, len) characters efficiently
35 # Using slice with negative index handles bounds automatically in Python
36 return "".join(self.left[-10:])