2296. Design a Text Editor - Detailed Explanation
Problem Statement
Design a text editor that initially contains an empty string and a cursor at the beginning. You must implement a class TextEditor
that supports the following operations:
- addText(text) – insert the string
text
at the cursor’s current position. After insertion, the cursor is at the end of the inserted text. - deleteText(k) – delete up to
k
characters to the left of the cursor. Return the number of characters actually deleted. Cursor ends up immediately after the deleted segment. - cursorLeft(k) – move the cursor left by up to
k
positions. Return the last up to 10 characters to the left of the new cursor position as a string. - cursorRight(k) – move the cursor right by up to
k
positions. Return the last up to 10 characters to the left of the new cursor position as a string.
Data Structure
Maintain two stacks (or deques/arrays used as stacks):
- left – characters to the left of the cursor, in order
- right – characters to the right of the cursor, in order
The cursor sits conceptually between the tops of these two stacks.
How Operations Work
addText(text)
Push each character of text
onto left. Cursor advances right as you push.
deleteText(k)
Pop up to k
characters from left, count how many you actually popped, and return that count.
cursorLeft(k)
Repeat up to k
times: if left is non‑empty, pop one char from left and push it onto right.
Then, collect up to the last 10 chars from left (peek the top 10 of the stack in reverse order) and return them as a string.
cursorRight(k)
Repeat up to k
times: if right is non‑empty, pop one char from right and push it onto left.
Then similarly return up to the last 10 chars from left.
Step‑by‑Step Example
editor = TextEditor()
editor.addText("hello") # left = ['h','e','l','l','o'], right = []
editor.addText(" world") # left = ['h','e','l','l','o',' ','w','o','r','l','d']
editor.deleteText(5) → 5 # deletes ' world', left = ['h','e','l','l','o']
editor.cursorLeft(3) → "hel" # moves cursor left 3: left=['h','e'], right=['l','l','o'], returns last 10 of left = "he"
editor.cursorRight(2) → "hell" # moves 'l','l' back: left=['h','e','l','l'], right=['o'], returns "hell"
Complexity Analysis
- Each operation runs in O(min(k, n)), where
n
is current text length. - Total work over all calls is O(total characters added + total moves), which meets constraints up to 2·10⁵ operations.
- Space is O(n), the total text size.
Python Code
Java Code
Common Mistakes
- Forgetting to stop when a stack is empty.
- Building the 10‑char preview inefficiently (should only look at at most 10 elements).
- Off‑by‑one when slicing the last 10 characters.
Edge Cases
- Deleting more chars than exist (should delete only what’s available).
- Moving cursor left/right at bounds (should clamp at 0 or end).
- Very long inserts followed by many small moves.
Related Problems
GET YOUR FREE
Coding Questions Catalog