Design a text editor with a cursor that can do the following:
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
Implement the TextEditor class:
TextEditor() Initializes the object with empty text.void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.Example 1:
Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
// The current text is "leet|".
// 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|".
textEditor.cursorRight(3); // return "etpractice"
// The current text is "leetpractice|".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
// The current text is "leet|practice".
// "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
// The current text is "|practice".
// Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
// The current text is "|practice".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
// The current text is "practi|ce".
// "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
Constraints:
1 <= text.length, k <= 40text consists of lowercase English letters.2 * 104 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.Follow-up: Could you find a solution with time complexity of O(k) per call?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are building a text editor that needs to handle typing, deleting, and moving the cursor around. The straightforward, brute force approach is to treat the text like a simple physical notebook where you blindly follow every single instruction from start to finish by literally rewriting the page or shifting everything over every time a change happens.
Here's how the algorithm would work step-by-step:
Instead of treating the text as one long string that requires constantly shifting letters around when we type or delete, we can split the text into two separate piles meeting at a blinking cursor. This clever physical separation lets us add and remove text instantly without having to scan through the entire document every time.
Here's how the algorithm would work step-by-step:
class TextEditor:
def __init__(self):
# Two stacks represent the cursor split point to avoid costly array shifting operations.
self.left_stack = []
self.right_stack = []
def add_text(self, text_to_add: str) -> None:
for character in text_to_add:
self.left_stack.append(character)
def delete_text(self, characters_to_delete: int) -> int:
deleted_count = 0
while self.left_stack and deleted_count < characters_to_delete:
self.left_stack.pop()
deleted_count += 1
return deleted_count
def cursor_left(self, steps_to_move: int) -> str:
moved_count = 0
while self.left_stack and moved_count < steps_to_move:
self.right_stack.append(self.left_stack.pop())
moved_count += 1
return self.get_recent_text()
def cursor_right(self, steps_to_move: int) -> str:
moved_count = 0
while self.right_stack and moved_count < steps_to_move:
self.left_stack.append(self.right_stack.pop())
moved_count += 1
return self.get_recent_text()
def get_recent_text(self) -> str:
# Taking up to ten characters from the left stack provides the trailing text context.
start_index = max(0, len(self.left_stack) - 10)
return "".join(self.left_stack[start_index:])| Case | How to Handle |
|---|---|
| Cursor movement offsets exceed the total text length | Clamp the cursor position between zero and the total length of the text buffer to prevent out of bounds errors |
| Deleting more characters than currently exist to the left of the cursor | Truncate the deletion range at the beginning of the text buffer and remove only the available characters |
| Inserting text while the cursor is positioned in the middle of existing text | Split the internal data structure at the cursor index to insert the new characters and stitch the parts back together efficiently |
| Text operations on a completely empty text editor | Initialize the editor with a zero length state and allow seamless insertion starting from the initial cursor position |
| Maximum sized inputs with hundreds of thousands of continuous insertions and deletions | Use a gap buffer or a rope data structure instead of a standard string to ensure logarithmic or constant time modifications |
| Operations that request returning text preceding the cursor when the cursor is at index zero | Return an empty string immediately since no characters exist to the left of the cursor |