Design a Text Editor
Design a Text Editor is a hard design data structures problem solved with the stack pattern.
The best approach, optimal (two stacks around the cursor), runs in O(k) per call (O(text.length) for addText) time and O(L) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from one string with a cursor index up.
Problem
Build a simple text editor with a cursor that starts in an empty document. addText(text) types text at the cursor, leaving the cursor after it. deleteText(k) erases up to k characters to the left of the cursor (backspace) and returns how many were actually erased. cursorLeft(k) and cursorRight(k) move the cursor up to k positions, stopping at the ends of the text, and return the last min(10, len) characters to the left of the cursor, where len is the number of characters left of it.
Examples
Example 1
- Input
TextEditor(), addText("algorithm"), cursorLeft(4), deleteText(3), addText("bum"), cursorRight(10), deleteText(20), cursorLeft(2)- Output
null, null, "algor", 3, null, "albumithm", 9, ""- Why
- Moving left 4 leaves "algor|ithm". Deleting 3 gives "al|ithm", and typing gives "album|ithm". Moving right stops after 4 steps at the end. Only 9 characters exist to delete, and then the text is empty.
Example 2
- Input
TextEditor(), addText("abcdefghijkl"), cursorLeft(1), cursorRight(5)- Output
null, null, "bcdefghijk", "cdefghijkl"- Why
- Only the last 10 characters to the left of the cursor are returned.
Constraints
1 <= text.length, k <= 40- text consists of lowercase English letters.
- At most
2 * 10^4calls in total to addText, deleteText, cursorLeft and cursorRight. - Aim for O(k) per call.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| One string with a cursor index | O(L) per edit, where L is the text length | O(L) |
| Optimal (two stacks around the cursor) | O(k) per call (O(text.length) for addText) | O(L) |
1One string with a cursor index
O(L) per edit, where L is the text lengthO(L)Store the whole text in one buffer and remember the cursor position. Inserting and deleting happen in the middle of the buffer, so every later character is shifted.
- addText: insert text at cursor, cursor += text.length.
- deleteText: d = min(k, cursor); remove [cursor - d, cursor); cursor -= d; return d.
- cursorLeft / cursorRight: clamp cursor - k to 0 or cursor + k to the length.
- Return the substring [max(0, cursor - 10), cursor).
class TextEditor {
private final StringBuilder sb = new StringBuilder();
private int cursor = 0;
public TextEditor() {}
public void addText(String text) {
sb.insert(cursor, text);
cursor += text.length();
}
public int deleteText(int k) {
int d = Math.min(k, cursor);
sb.delete(cursor - d, cursor);
cursor -= d;
return d;
}
public String cursorLeft(int k) {
cursor = Math.max(0, cursor - k);
return sb.substring(Math.max(0, cursor - 10), cursor);
}
public String cursorRight(int k) {
cursor = Math.min(sb.length(), cursor + k);
return sb.substring(Math.max(0, cursor - 10), cursor);
}
}class TextEditor:
def __init__(self):
self.s = ""
self.cursor = 0
def addText(self, text: str) -> None:
self.s = self.s[:self.cursor] + text + self.s[self.cursor:]
self.cursor += len(text)
def deleteText(self, k: int) -> int:
d = min(k, self.cursor)
self.s = self.s[:self.cursor - d] + self.s[self.cursor:]
self.cursor -= d
return d
def cursorLeft(self, k: int) -> str:
self.cursor = max(0, self.cursor - k)
return self.s[max(0, self.cursor - 10):self.cursor]
def cursorRight(self, k: int) -> str:
self.cursor = min(len(self.s), self.cursor + k)
return self.s[max(0, self.cursor - 10):self.cursor]class TextEditor {
string s;
int cursor = 0;
public:
TextEditor() {}
void addText(string text) {
s.insert(cursor, text);
cursor += (int)text.size();
}
int deleteText(int k) {
int d = min(k, cursor);
s.erase(cursor - d, d);
cursor -= d;
return d;
}
string cursorLeft(int k) {
cursor = max(0, cursor - k);
int from = max(0, cursor - 10);
return s.substr(from, cursor - from);
}
string cursorRight(int k) {
cursor = min((int)s.size(), cursor + k);
int from = max(0, cursor - 10);
return s.substr(from, cursor - from);
}
};class TextEditor {
constructor() {
this.s = "";
this.cursor = 0;
}
addText(text) {
this.s = this.s.slice(0, this.cursor) + text + this.s.slice(this.cursor);
this.cursor += text.length;
}
deleteText(k) {
const d = Math.min(k, this.cursor);
this.s = this.s.slice(0, this.cursor - d) + this.s.slice(this.cursor);
this.cursor -= d;
return d;
}
cursorLeft(k) {
this.cursor = Math.max(0, this.cursor - k);
return this.s.slice(Math.max(0, this.cursor - 10), this.cursor);
}
cursorRight(k) {
this.cursor = Math.min(this.s.length, this.cursor + k);
return this.s.slice(Math.max(0, this.cursor - 10), this.cursor);
}
}2Optimal (two stacks around the cursor)
O(k) per call (O(text.length) for addText)O(L)Keep the characters left of the cursor in one stack and the characters right of it in another, each with its top next to the cursor. Typing pushes onto the left stack, deleting pops from it, and moving the cursor transfers characters between the stacks one at a time. Nothing far from the cursor is ever touched.
- left holds the text before the cursor in order; right holds the text after the cursor reversed.
- addText: append every character to left.
- deleteText: d = min(k, left.size); pop d characters from left; return d.
- cursorLeft: up to k times, move left's top to right. cursorRight: the reverse.
- Return the last min(10, left.size) characters of left.
class TextEditor {
private final StringBuilder left = new StringBuilder();
private final StringBuilder right = new StringBuilder();
public TextEditor() {}
public void addText(String text) {
left.append(text);
}
public int deleteText(int k) {
int d = Math.min(k, left.length());
left.setLength(left.length() - d);
return d;
}
public String cursorLeft(int k) {
while (k-- > 0 && left.length() > 0) {
right.append(left.charAt(left.length() - 1));
left.setLength(left.length() - 1);
}
return lastTen();
}
public String cursorRight(int k) {
while (k-- > 0 && right.length() > 0) {
left.append(right.charAt(right.length() - 1));
right.setLength(right.length() - 1);
}
return lastTen();
}
private String lastTen() {
return left.substring(Math.max(0, left.length() - 10));
}
}class TextEditor:
def __init__(self):
self.left = []
self.right = []
def addText(self, text: str) -> None:
self.left.extend(text)
def deleteText(self, k: int) -> int:
d = min(k, len(self.left))
for _ in range(d):
self.left.pop()
return d
def cursorLeft(self, k: int) -> str:
while k > 0 and self.left:
self.right.append(self.left.pop())
k -= 1
return "".join(self.left[-10:])
def cursorRight(self, k: int) -> str:
while k > 0 and self.right:
self.left.append(self.right.pop())
k -= 1
return "".join(self.left[-10:])class TextEditor {
string left, right;
string lastTen() {
int from = max(0, (int)left.size() - 10);
return left.substr(from);
}
public:
TextEditor() {}
void addText(string text) {
left += text;
}
int deleteText(int k) {
int d = min(k, (int)left.size());
left.resize(left.size() - d);
return d;
}
string cursorLeft(int k) {
while (k-- > 0 && !left.empty()) {
right.push_back(left.back());
left.pop_back();
}
return lastTen();
}
string cursorRight(int k) {
while (k-- > 0 && !right.empty()) {
left.push_back(right.back());
right.pop_back();
}
return lastTen();
}
};class TextEditor {
constructor() {
this.left = [];
this.right = [];
}
addText(text) {
for (const c of text) this.left.push(c);
}
deleteText(k) {
const d = Math.min(k, this.left.length);
this.left.length -= d;
return d;
}
cursorLeft(k) {
while (k-- > 0 && this.left.length > 0) this.right.push(this.left.pop());
return this.lastTen();
}
cursorRight(k) {
while (k-- > 0 && this.right.length > 0) this.left.push(this.right.pop());
return this.lastTen();
}
lastTen() {
return this.left.slice(Math.max(0, this.left.length - 10)).join("");
}
}Edge cases to test
- Deleting or moving more characters than exist on that side of the cursor
- Calls on an empty editor (delete returns 0, moves return an empty string)
- Fewer than 10 characters to the left of the cursor
- Typing in the middle of the text, not only at the end
Hints
Hint 1
Everything happens at the cursor. Split the text into the part left of the cursor and the part right of it.
Hint 2
Keep both parts as stacks whose tops touch the cursor; the right part is stored reversed.
Hint 3
Moving the cursor one step pops a character from one stack and pushes it onto the other.
FAQ
What is the best time complexity for Design a Text Editor?
Optimal (two stacks around the cursor) runs in O(k) per call (O(text.length) for addText) time and O(L) extra space.
Which pattern does Design a Text Editor use?
It is a design data structures problem that uses the stack pattern. Other problems with the same pattern: Min Stack, Design a Stack With Increment Operation, Maximum Frequency Stack.
Is there a brute force solution for Design a Text Editor?
Yes. One string with a cursor index takes O(L) per edit, where L is the text length time and O(L) space. Store the whole text in one buffer and remember the cursor position.
Which edge cases should I test for Design a Text Editor?
Deleting or moving more characters than exist on that side of the cursor; Calls on an empty editor (delete returns 0, moves return an empty string); Fewer than 10 characters to the left of the cursor; Typing in the middle of the text, not only at the end.