Taro Logo

Design a Text Editor

#1 Most AskedHard
Topics:
StringsStacks

Design a text editor with a cursor that can do the following:

  • Add text to where the cursor is.
  • Delete text from where the cursor is (simulating the backspace key).
  • Move the cursor either left or right.

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 <= 40
  • text consists of lowercase English letters.
  • At most 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?

Solution


Clarifying Questions

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:

  1. What is the maximum length of the text we can expect, and what are the constraints on the number of operations (insertions, deletions, cursor shifts) that will be performed?
  2. When the cursor moves left or right by a given offset, what should happen if the offset exceeds the boundaries of the text (e.g., trying to move past the very beginning or end of the document)?
  3. How are the deletion operations defined—do we delete characters to the left of the cursor (backspace style) or to the right of the cursor (delete style), and how is the return value formatted?
  4. What character set should we support? Are we dealing strictly with standard ASCII characters, or do we need to handle multi-byte Unicode/emoji characters where a single character might span multiple code units?
  5. When returning the text preceding the cursor (or the text segments), is there a strict character limit on what should be returned—for example, returning only the last $k$ characters before the cursor as seen in standard text editor APIs?

Brute Force Solution

Approach

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:

  1. Start with a blank sheet of paper to represent your empty document and keep track of where your pen currently points.
  2. Whenever a letter is typed, squeeze it into the document right where the pen points and shift every single letter that comes after it one spot to the right.
  3. Whenever a deletion happens, erase the letter right before where the pen points and shift all the remaining letters on the page one spot to the left to fill the gap.
  4. Whenever the cursor needs to move left or right, pick up your pen and physically walk it over letter by letter until you reach the requested spot.
  5. Whenever the cursor needs to move to the very beginning or end, walk your pen all the way across the document step by step.
  6. Whenever you need to delete a chunk of text looking backwards, repeat the single-deletion process over and over until the requested number of letters are gone.
  7. Whenever you need to read back a portion of the text, scan the page starting from the beginning and count out the exact letters requested until you have your answer.

Code Implementation

Big(O) Analysis

Time Complexity
O(k * n) – For operations like typing or deleting a single character, shifting all subsequent letters in the text takes time proportional to the current length of the document, let us call it n. When we perform cursor movements or deletions of a chunk containing k characters, we repeat these linear-time shifts or step-by-step walks k times. If k operations each take up to n steps in the worst case, the total work approximates k * n operations. Simplifying this product yields a worst-case Big O time complexity of O(k * n) for those operations.
Space Complexity
O(N) – The auxiliary space is driven by the physical document representation holding the characters, where N represents the total number of characters present in the text editor at any given time. As typing operations add characters to the document, the data structure expands linearly to store these elements. There are no recursive call stacks or significant temporary variables utilized during standard operations that would scale beyond the primary document storage. Thus, the total extra memory required strictly scales in direct proportion to the size of the text N.

Optimal Solution

Approach

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:

  1. Imagine your text editor is like a book split right down the middle where the blinking cursor sits.
  2. Keep all the text to the left of the cursor in one stack, and all the text to the right of the cursor in a separate stack facing the opposite direction.
  3. When you type new letters, simply drop them onto the top of the left stack so they appear right before the cursor.
  4. When you delete a letter, just remove the top piece from the left stack, which acts just like hitting the backspace key.
  5. When you need to move the cursor left or right, take letters off the top of one stack and flip them over to the top of the other stack, like moving bookmarks.
  6. When you need to pull up text from the very end of the document, just peek into the right stack to see what is waiting there.
  7. By managing two opposing stacks instead of shifting a giant single line of text, every typing and moving action happens instantly no matter how long the document grows.

Code Implementation

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:])

Big(O) Analysis

Time Complexity
–
Space Complexity
O(N) – The extra memory is driven by the two opposing stacks used to simulate the left and right sides of the text editor cursor. Across all typing, deleting, and cursor-shifting operations, every character inserted into the document is ultimately stored in one of these two stacks. Letting N represent the total number of characters currently held in the text editor, the combined storage of the left and right stacks scales directly with N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Edge Cases

Cursor movement offsets exceed the total text length
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Return an empty string immediately since no characters exist to the left of the cursor
0/1 completed