Design a Text Editor

Hard Design Data Structures Stack

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^4 calls 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.

00:00
Testcase

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.

ApproachTimeSpace
One string with a cursor indexO(L) per edit, where L is the text lengthO(L)
Optimal (two stacks around the cursor)O(k) per call (O(text.length) for addText)O(L)

1One string with a cursor index

TimeO(L) per edit, where L is the text length
SpaceO(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.

  1. addText: insert text at cursor, cursor += text.length.
  2. deleteText: d = min(k, cursor); remove [cursor - d, cursor); cursor -= d; return d.
  3. cursorLeft / cursorRight: clamp cursor - k to 0 or cursor + k to the length.
  4. 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);
    }
}

2Optimal (two stacks around the cursor)

TimeO(k) per call (O(text.length) for addText)
SpaceO(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.

  1. left holds the text before the cursor in order; right holds the text after the cursor reversed.
  2. addText: append every character to left.
  3. deleteText: d = min(k, left.size); pop d characters from left; return d.
  4. cursorLeft: up to k times, move left's top to right. cursorRight: the reverse.
  5. 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));
    }
}

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.