15% off all plans & roadmaps Use code

See plans

Design a Text Editor

Updated

TL;DR: You add text, delete to the left of the cursor and move the cursor, and each call returns the last 10 characters before it. Keeping the text on each side of the cursor in two stacks makes every call cost O(k).

Problem

Design a text editor with a cursor. The editor supports three actions:

  • Add text at the cursor.
  • Delete text to the left of the cursor, the way the backspace key does.
  • Move the cursor left or right.

Deletion only removes characters to the left of the cursor. The cursor stays inside the text and cannot move past either end, so 0 <= cursor.position <= currentText.length always holds.

Implement the TextEditor class:

  • TextEditor() starts with empty text.
  • void addText(string text) appends text at the cursor. The cursor ends to the right of text.
  • int deleteText(int k) deletes k characters to the left of the cursor. It returns the number of characters actually deleted.
  • string cursorLeft(int k) moves the cursor left k times. It 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 right k times. It returns the last min(10, len) characters to the left of the cursor, using the same rule.

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:
The | marks the cursor. After addText(leetcode) the text is leetcode|. deleteText(4) returns 4 and leaves leet|. Then addText(practice) gives leetpractice|.

cursorRight(3) cannot move, so it returns etpractice, the last 10 characters left of the cursor. cursorLeft(8) moves the cursor to leet|practice and returns leet. deleteText(10) removes 4 characters and returns 4, leaving |practice.

cursorLeft(2) cannot move and returns the empty string. cursorRight(6) moves the cursor to practi|ce and returns practi.

Constraints

  • 1 <= text.length, k <= 40
  • text consists of lowercase English letters.
  • At most 2 * 10^4 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.

Constraints that matter

  • Up to 2 * 10^4 calls with up to 40 characters each means the text can reach about 8 * 10^5 characters. Copying the whole text on every edit is too slow.
  • k is at most 40, so a loop that moves the cursor one character per step costs at most 40 steps per call.
  • The returned window is at most 10 characters, so reading it costs a constant amount no matter how long the text is.
  • Edits happen only at the cursor, so the solution never needs to touch characters far from it.

View on LeetCode

Hints

Hint 1

The cursor splits the text into two halves, and every action happens at that split.

Hint 2

Store the whole document as one string and keep an integer cursor that counts the characters to its left.

Solution

Intuition

The cursor splits the text into two halves, and every action happens at that split. Typing adds to the left half, backspace removes from it, and moving the cursor carries characters across the split. This is the two stacks pattern. A stack only exposes its top, and the cursor only ever touches the characters next to it.

Picture a row of books with a bookmark lying between two stacks. The left stack holds the books before the bookmark with the nearest on top, and moving the bookmark carries books from one stack to the other.

The statement gives two hints. Edits happen only at the cursor, and each call moves the cursor at most 40 positions. So the solution should never shift characters that sit far from the cursor. The window is capped at 10 characters, so reading it also costs a constant.

Keep the characters left of the cursor in one stack, with the nearest character on top. Keep the characters right of the cursor in a second stack, also with the nearest character on top. Read the left stack from bottom to top, then the right stack from top to bottom, and you get the full text in order.

Watch the pattern animation

Worked example

Input: constructor takes no arguments
addText(a), deleteText(5), cursorLeft(1), addText(b), cursorRight(2)
argument lists: [], ["a"], [5], [1], ["b"], [2]
Output: [null, null, 1, "", null, "b"]
Explanation: The text starts empty. addText(a) leaves the cursor after a. deleteText(5) can only remove 1 character, so it returns 1 and the text is empty. cursorLeft(1) cannot move, so it returns the empty string. addText(b) puts b before the cursor. cursorRight(2) cannot move past the end, so it returns b.

Approach 1: Brute force: one string and an index

Store the whole document as one string and keep an integer cursor that counts the characters to its left. To add text, build a new string from the part before the cursor, the new text and the part after the cursor. Deletion and cursor moves use the same slicing idea, and the window is a slice of the characters just before the cursor.

Steps

  1. Store the document in doc and the cursor position in cursor, both starting empty and at 0.
  2. For addText, set doc to the slice before the cursor, then the new text, then the slice after the cursor. Add the length of the text to cursor.
  3. For deleteText, count removed as min(k, cursor). Rebuild doc without the removed characters and subtract removed from cursor.
  4. For cursorLeft and cursorRight, clamp cursor to the range from 0 to the length of doc after adding or subtracting k.
  5. Return doc from max(0, cursor - 10) up to cursor for every cursor method.

Dry run

Start with doc empty and cursor 0.

  1. addText(a): doc becomes a and cursor becomes 1.
  2. deleteText(5): removed is min(5, 1) = 1. doc becomes the empty string and cursor becomes 0. Return 1.
  3. cursorLeft(1): cursor stays at 0 because it cannot go below 0. The window is empty, so return the empty string.
  4. addText(b): doc becomes b and cursor becomes 1.
  5. cursorRight(2): cursor becomes min(1, 1 + 2) = 1. The window is doc from 0 up to 1, which is b. Return b.

The last return value is b, which matches the expected output.

Complexity

TimeO(N) per addText or deleteText, O(1) per cursor move
SpaceO(N)

Let N be the length of the text when the call starts. addText and deleteText build a new string, and building it copies about N characters, so each of those calls costs O(N). cursorLeft and cursorRight change one integer, and the window copies at most 10 characters, so they cost O(1). With up to 2 * 10^4 calls and a text that can reach 8 * 10^5 characters, the total work can reach billions of character copies.

PythonTested in our runner

class TextEditor:
    def __init__(self):
        self.doc = ""
        self.cursor = 0

    def addText(self, text: str) -> None:
        self.doc = self.doc[:self.cursor] + text + self.doc[self.cursor:]
        self.cursor += len(text)

    def deleteText(self, k: int) -> int:
        removed = min(k, self.cursor)
        self.doc = self.doc[:self.cursor - removed] + self.doc[self.cursor:]
        self.cursor -= removed
        return removed

    def cursorLeft(self, k: int) -> str:
        self.cursor = max(0, self.cursor - k)
        return self._window()

    def cursorRight(self, k: int) -> str:
        self.cursor = min(len(self.doc), self.cursor + k)
        return self._window()

    def _window(self) -> str:
        return self.doc[max(0, self.cursor - 10):self.cursor]

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: Two stacks split at the cursorOptimalDesign (General/Specific)

What's slow: every insert or delete rebuilds the whole string, which copies every character after the cursor, and the cursor never reads those copies. The insight that fixes it: the cursor only touches the characters next to it, so keep the characters before the cursor in one stack and the characters after it in another. Then each edit and each move works on the top of a stack.

Why it is correct. The two stacks always hold the text exactly, with left as the characters before the cursor in order and right as the characters after it reversed. Every operation either moves characters across the cursor or removes the ones directly beside it, so this split stays true after each call. Reading the top ten of left therefore gives the last characters before the cursor, which is exactly what the problem asks for.

Steps

  1. Create left for the characters before the cursor, with the nearest character on top.
  2. Create right for the characters after the cursor, stored reversed, so the nearest character is on top.
  3. For addText, push each character of the text onto left.
  4. For deleteText, pop up to k characters from left, count the pops and return the count.
  5. For cursorLeft, move up to k characters from the top of left to the top of right.
  6. For cursorRight, move up to k characters from the top of right to the top of left.
  7. After any move or edit, return the last min(10, len) characters of left, read from bottom to top.

Dry run

The example is short, so the moves find nothing to move. The table also shows the empty-stack checks.

Callleft (bottom to top)right (top is nearest)Returns
startemptyempty
addText(a)aemptynull
deleteText(5)emptyempty1
cursorLeft(1)emptyemptyempty string
addText(b)bemptynull
cursorRight(2)bemptyb

The final row returns b, which matches the expected output.

Complexity

TimeO(k) per call
SpaceO(N)

Let k be the argument of the call and N the number of characters stored. addText pushes len(text) characters, deleteText pops at most k, and each cursor move transfers at most k characters with one O(1) push and pop per character. The window reads at most 10 characters from the top of left, so each call does O(k + 10), which is O(k) because k is at least 1. Every stored character sits in exactly one stack, so the space is O(N).

PythonTested in our runner

from typing import List, Optional

class TextEditor:
    def __init__(self):
        self.left = []   # characters before the cursor, last item is nearest
        self.right = []  # characters after the cursor, reversed, last item is nearest

    def addText(self, text: str) -> None:
        self.left.extend(text)

    def deleteText(self, k: int) -> int:
        count = 0
        while count < k and self.left:
            self.left.pop()
            count += 1
        return count

    def cursorLeft(self, k: int) -> str:
        for _ in range(k):
            if not self.left:
                break
            self.right.append(self.left.pop())
        return self._window()

    def cursorRight(self, k: int) -> str:
        for _ in range(k):
            if not self.right:
                break
            self.left.append(self.right.pop())
        return self._window()

    def _window(self) -> str:
        return "".join(self.left[-10:])

Common mistakes

  • Taking the window before the move loop, as in window = self._window() above for _ in range(k). The returned text must describe the cursor after the move. Return the window after the loop.
  • Using self.left[:10] or left.substr(0, 10) for the window. That returns the first characters of the whole text, not the ones nearest the cursor. Take the last 10 characters of the left side instead.
  • Returning k from deleteText. The problem asks for the number of characters actually deleted, which is smaller when the text is short. Count the pops and return that count.
  • Popping in a loop without checking for empty, such as left.pop() repeated k times. Python raises IndexError on an empty list. Loop while the count is below k and the stack is not empty.
  • Calling left.substring(len - 10) in Java when the text has fewer than 10 characters. That throws StringIndexOutOfBoundsException. Clamp the start index at 0 with Math.max.

Edge cases

  • Empty text: deleteText(5) returns 0, and cursorLeft(3) returns the empty string with the cursor still at 0.
  • Single character: addText(a) then deleteText(1) returns 1, and a second deleteText(1) returns 0.
  • Cursor at the end with a request larger than the text: addText(ab) then cursorRight(40) returns ab and the cursor stays at the end.
  • Deletion larger than the text: addText(abc) then deleteText(40) returns 3 and leaves the text empty.
  • Long text: after addText of 40 characters, the window returns exactly the last 10 characters, not all 40.
  • Short left side: addText(abcdef) then cursorLeft(3) returns abc because min(10, 3) is 3.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Design a Text Editor, with how to answer them.

Unlock the follow-ups

Design a Text Editor FAQ

What is the time complexity of Design a Text Editor?

With two stacks, each call costs O(k), where k is its argument, plus a constant for the 10-character window. A single string costs O(N) for each addText or deleteText, where N is the current text length. The proof is in the complexity section above.

Why use two stacks for Design a Text Editor?

Every edit and every cursor move happens next to the cursor. A stack gives constant-time access to its top, so the cursor can move characters across the split without shifting the rest of the text.

Can Design a Text Editor be solved in O(1) extra space?

No, because the editor has to store every character, so the text alone takes O(N) space. Beyond that storage, the algorithm uses O(1) extra space plus the 10-character result string.

Is slicing the last 10 characters safe when the text is shorter than 10?

In Python, left[-10:] returns the whole list when it has fewer than 10 items, so it is safe. In Java, substring(len - 10) throws when len is below 10, so clamp the start index at 0.

Why does cursorLeft return only 10 characters?

The problem defines the return value as the last min(10, len) characters left of the cursor. Reading from the top of the left stack gives those characters directly, and it costs a constant.

Asked at

See which companies ask this — Pro

Practise it