Stateful Document Cursor with Typing, Deletion, and 2D Movement

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Build a TextEditor class representing an editable text document with a single active cursor, and execute command sequences against a fresh editor instance through run_text_editor(operations, arguments).

Upon creation, the document is empty and the cursor rests at index 0 (so rendering immediately yields "|"). Implement these four operations:

  • type_in ([char]): Place char directly ahead of the cursor, advancing the cursor so it sits immediately after char. Line breaks are typed as "\n". Appends None to the output list.
  • backspace ([]): Remove the character directly to the left of the cursor. Calling backspace when the cursor is at index 0 makes no change; removing a "\n" fuses the current line onto the tail of the line above it. Appends None to the output list.
  • move_cursor ([direction]): Reposition the cursor based on direction and append None to the output list:
    • "left" and "right" advance the cursor one character backward or forward (stepping across "\n" between neighboring lines), doing nothing when already at index 0 or at the end of the document.
    • "up" and "down" move to the preceding or following "\n"-delimited line. With col denoting the number of characters before the cursor on its current line, the cursor lands at offset min(col, destination_line_length) of the target line (without retaining any sticky column from prior moves). Calling "up" on the initial line or "down" on the final line leaves the cursor where it is.
  • __str__ ([]): Append str(editor) to the output list, defined as the complete document string with "|" spliced in at the cursor's current offset.

Return the list of outputs collected across all (operation, argument_list) pairs.

Examples

Example 1

Input:
  operations = ["__str__", "type_in", "type_in", "type_in", "__str__", "backspace", "__str__"]
  arguments  = [[], ["l"], ["o"], ["g"], [], [], []]

Output:
  ["|", None, None, None, "log|", None, "lo|"]

Explanation: A brand-new editor renders "|". Typing 'l', 'o', and 'g' builds "log|", and a single backspace deletes 'g' to produce "lo|".

Example 2

Input:
  operations = ["type_in", "type_in", "type_in", "move_cursor", "__str__", "type_in", "__str__", "backspace", "move_cursor", "__str__"]
  arguments  = [["n"], ["e"], ["t"], ["left"], [], ["x"], [], [], ["right"], []]

Output:
  [None, None, None, None, "ne|t", None, "nex|t", None, None, "net|"]

Explanation: After typing "net|", stepping "left" yields "ne|t". Typing 'x' inserts at the cursor ("nex|t"), backspace removes 'x' ("ne|t"), and stepping "right" returns to "net|".

Example 3

Input:
  operations = ["type_in", "type_in", "type_in", "type_in", "type_in", "type_in", "type_in", "move_cursor", "move_cursor", "__str__", "move_cursor", "__str__"]
  arguments  = [["s"], ["k"], ["y"], ["\n"], ["s"], ["e"], ["a"], ["left"], ["left"], [], ["up"], []]

Output:
  [None, None, None, None, None, None, None, None, None, "sky\ns|ea", None, "s|ky\nsea"]

Explanation: Typing "sky\nsea" puts the cursor at column 3 of the second line ("sky\nsea|"). Two "left" steps move it to column 1 ("sky\ns|ea"), and moving "up" preserves column 1 on the three-character first line ("s|ky\nsea").

Constraints

  • 1 <= len(operations) == len(arguments) <= 10^5
  • Each operation name is "type_in", "backspace", "move_cursor", or "__str__".
  • Each "move_cursor" argument is "left", "right", "up", or "down".
  • Document characters never include "|", and lines break strictly at "\n" characters (no fixed-width wrapping).
  • Typing, backspacing, and "left" / "right" moves must run in $O(1)$ amortized time per call.

Step-by-step walkthrough

  1. Pin down the document rules first

    run_text_editor(operations, arguments) executes commands on a fresh TextEditor. Mutating methods ("type_in", "backspace", "move_cursor") produce None, while "__str__" produces str(editor).

    Before selecting a data structure, state the exact boundary rules:

    • Initial state: an empty document places the cursor at index 0, rendering as "|".
    • Document boundaries: backspace() and "left" at index 0 leave state untouched; "right" at the end of the document leaves state untouched.
    • Line breaks ("\n"): lines break exclusively at "\n" characters. "left" and "right" cross "\n" as a single character between adjacent lines, and backspace() immediately after "\n" removes the newline to fuse the two lines.
    • Vertical navigation ("up" and "down"): preserve the cursor's current column col, or clamp to min(col, target_line_len) when the destination line is shorter (using the clamped column on later moves rather than remembering a sticky column). Calling "up" on line 0 or "down" on the final line is a no-op.
  2. Why a single string or single list falls short

    Keeping the document as a Python str plus an integer cursor copies the entire string on every keystroke because Python strings are immutable:

    def type_with_string(text: str, cursor: int, ch: str):
        return text[:cursor] + ch + text[cursor:], cursor + 1
    

    Even a single Python list of characters with chars.insert(cursor, ch) and chars.pop(cursor - 1) shifts every character after cursor by one slot:

    Single list when inserting 'x' into "ne|t... (1,000,000 chars)":
      ['n', 'e', 't', 'p', 'q', ...]
                  ^-- every character from here onward shifts right by 1! -> O(n)
    

    Since mutations happen right at the cursor, we want both sides of the cursor to sit at the tail of a Python list where .append() and .pop() run in constant time.

  3. Key idea: two stacks facing each other across the cursor

    Divide the document at the cursor into two lists used as stacks (last-in, first-out sequences touched only at their end):

    • self.left: characters preceding the cursor in left-to-right reading order (self.left[-1] sits right before |).
    • self.right: characters following the cursor in reverse order (self.right[-1] sits right after | instead of sitting at index 0).
    Document rendered as:  "ne|xt"
    
      self.left (normal order)        cursor        self.right (reversed order)
      +-----+-----+                     |             +-----+-----+
      | 'n' | 'e' |  <-- left[-1]       |   right[-1] | 'x' | 't' |  (stored as ['t', 'x'])
      +-----+-----+                     |             +-----+-----+
    

    Now type_in appends onto self.left, backspace pops self.left, and __str__ concatenates self.left, "|", and reversed(self.right):

    class TextEditor:
        def __init__(self) -> None:
            # Characters to the left of the cursor, in reading order: e.g. ['n', 'e'].
            self.left: List[str] = []
            # Characters to the right of the cursor, in reverse order so self.right[-1]
            # is the character immediately after the cursor: e.g. ['t', 'x'] for "...|xt".
            self.right: List[str] = []
    
        def type_in(self, char: str) -> None:
            # Push each incoming character right before the cursor (onto `self.left`).
            for ch in char:
                self.left.append(ch)
    
        def backspace(self) -> None:
            # Guard against an empty left stack when the cursor is at index 0.
            if self.left:
                self.left.pop()
    
        def __str__(self) -> str:
            # Rebuild the full document: left side in order, '|', then right side un-reversed.
            before_cursor = "".join(self.left)
            after_cursor = "".join(reversed(self.right))
            return before_cursor + "|" + after_cursor
    
  4. Part 2: Stepping left and right in O(1) time

    Stepping horizontally flips which side of the cursor one character belongs to:

    • Step left: pop self.left[-1] and append it onto self.right.
    • Step right: pop self.right[-1] and append it onto self.left.
    Start ("net|"):        left = ['n', 'e', 't']    right = []
    move_cursor("left"):   left = ['n', 'e']         right = ['t']    -> "ne|t"
    type_in("x"):          left = ['n', 'e', 'x']    right = ['t']    -> "nex|t"
    backspace():           left = ['n', 'e']         right = ['t']    -> "ne|t"
    move_cursor("right"):  left = ['n', 'e', 't']    right = []       -> "net|"
    

    Both helpers take O(1) time and preserve the invariant for subsequent edits:

        def _step_left(self) -> None:
            # Moving the cursor left by 1 puts the character before the cursor onto the right side.
            if self.left:
                ch = self.left.pop()
                self.right.append(ch)
    
        def _step_right(self) -> None:
            # Moving the cursor right by 1 pulls the nearest right-side character (self.right[-1]) onto left.
            if self.right:
                ch = self.right.pop()
                self.left.append(ch)
    
  5. Part 3: Measuring columns and jumping up or down

    Vertical navigation relies on two local measurements around the cursor:

    1. _column(): count characters backward from self.left[-1] up to the nearest "\n" (or start of text).
    2. _rest_of_line(): count characters backward from self.right[-1] up to the nearest "\n" (or end of text). Because self.right is reversed, walking backward from self.right[-1] scans forward in reading order!

    How moving up executes: - When current_col == len(self.left), no "\n" exists before the cursor, so the cursor is already on line 0 — return early. - Otherwise, step left current_col + 1 times to cross the current_col characters on this line plus the preceding "\n", landing at the very end of the line above. - Measure prev_line_len = self._column(), compute target_col = min(current_col, prev_line_len), and step left prev_line_len - target_col additional times.

    Example 3: "sky\ns|ea"  (current_col = 1)
    
      1. Step left current_col + 1 = 2 times (cross 's' and '\n'):
         "sky|\nsea"   -> cursor sits at the end of line 0, so prev_line_len = 3
    
      2. target_col = min(1, 3) = 1. Step left (3 - 1) = 2 more times:
         "s|ky\nsea"   -> cursor lands at column 1 of line 0!
    

    Moving down is symmetric: when chars_to_line_end == len(self.right), we are already on the final line; otherwise step right chars_to_line_end + 1 times to reach column 0 of the next line, read next_line_len = self._rest_of_line(), and step right min(current_col, next_line_len) times.

        def _column(self) -> int:
            """Count characters between the start of the current line and the cursor."""
            col = 0
            idx = len(self.left) - 1
            # Scan backward from just before the cursor until we hit a newline or the start of text.
            while idx >= 0 and self.left[idx] != "\n":
                col += 1
                idx -= 1
            return col
    
        def _rest_of_line(self) -> int:
            """Count characters between the cursor and the end of the current line."""
            remaining = 0
            idx = len(self.right) - 1
            # Because `self.right` is reversed, scanning backward from the end of `self.right`
            # walks forward in the document starting right after the cursor.
            while idx >= 0 and self.right[idx] != "\n":
                remaining += 1
                idx -= 1
            return remaining
    
        def _move_up(self) -> None:
            current_col = self._column()
            # If every character in `self.left` belongs to the current line, there is no '\n'
            # before the cursor, which means we are already on the first line.
            if current_col == len(self.left):
                return
    
            # Step left `current_col` times to reach column 0 of the current line,
            # plus 1 more step to cross the '\n' and land at the very end of the previous line.
            for _ in range(current_col + 1):
                self._step_left()
    
            # Since the cursor now sits at the end of the previous line, `_column()` equals its length.
            prev_line_len = self._column()
            target_col = min(current_col, prev_line_len)
            steps_from_line_end = prev_line_len - target_col
            for _ in range(steps_from_line_end):
                self._step_left()
    
        def _move_down(self) -> None:
            current_col = self._column()
            chars_to_line_end = self._rest_of_line()
            # If every character in `self.right` belongs to the current line, there is no '\n'
            # after the cursor, which means we are already on the last line.
            if chars_to_line_end == len(self.right):
                return
    
            # Step right `chars_to_line_end` times to reach the '\n' at the end of this line,
            # plus 1 more step to cross '\n' and land at column 0 of the next line.
            for _ in range(chars_to_line_end + 1):
                self._step_right()
    
            # Since the cursor now sits at column 0 of the next line, `_rest_of_line()` equals its length.
            next_line_len = self._rest_of_line()
            target_col = min(current_col, next_line_len)
            for _ in range(target_col):
                self._step_right()
    
  6. Connect `move_cursor` and `run_text_editor`

    move_cursor routes "left", "right", "up", and "down" to the four helpers, and run_text_editor replays the command list on one TextEditor instance:

    def run_text_editor(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]:
        editor = TextEditor()
        results: List[Optional[str]] = []
    
        # Replay each command in sequence; only "__str__" returns a string, while mutations return None.
        for op, args in zip(operations, arguments):
            if op == "type_in":
                editor.type_in(args[0])
                results.append(None)
            elif op == "backspace":
                editor.backspace()
                results.append(None)
            elif op == "move_cursor":
                editor.move_cursor(args[0])
                results.append(None)
            elif op == "__str__":
                results.append(str(editor))
            else:
                raise ValueError(f"unknown operation {op!r}")
    
        return results
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TextEditor:
        """A cursor-based text editor stored as two character stacks around the cursor.
    
        Example for rendered text "ne|xt":
          - self.left  = ['n', 'e']  (normal left-to-right order; 'e' is right before '|')
          - self.right = ['t', 'x']  (reversed order; 'x' is right after '|', at self.right[-1])
        """
    
        def __init__(self) -> None:
            # Characters to the left of the cursor, in reading order: e.g. ['n', 'e'].
            self.left: List[str] = []
            # Characters to the right of the cursor, in reverse order so self.right[-1]
            # is the character immediately after the cursor: e.g. ['t', 'x'] for "...|xt".
            self.right: List[str] = []
    
        def type_in(self, char: str) -> None:
            # Push each incoming character right before the cursor (onto `self.left`).
            for ch in char:
                self.left.append(ch)
    
        def backspace(self) -> None:
            # Guard against an empty left stack when the cursor is at index 0.
            if self.left:
                self.left.pop()
    
        def __str__(self) -> str:
            # Rebuild the full document: left side in order, '|', then right side un-reversed.
            before_cursor = "".join(self.left)
            after_cursor = "".join(reversed(self.right))
            return before_cursor + "|" + after_cursor
    
        def move_cursor(self, direction: str) -> None:
            if direction == "left":
                self._step_left()
            elif direction == "right":
                self._step_right()
            elif direction == "up":
                self._move_up()
            elif direction == "down":
                self._move_down()
            else:
                raise ValueError(f"unknown direction {direction!r}")
    
        def _step_left(self) -> None:
            # Moving the cursor left by 1 puts the character before the cursor onto the right side.
            if self.left:
                ch = self.left.pop()
                self.right.append(ch)
    
        def _step_right(self) -> None:
            # Moving the cursor right by 1 pulls the nearest right-side character (self.right[-1]) onto left.
            if self.right:
                ch = self.right.pop()
                self.left.append(ch)
    
        def _column(self) -> int:
            """Count characters between the start of the current line and the cursor."""
            col = 0
            idx = len(self.left) - 1
            # Scan backward from just before the cursor until we hit a newline or the start of text.
            while idx >= 0 and self.left[idx] != "\n":
                col += 1
                idx -= 1
            return col
    
        def _rest_of_line(self) -> int:
            """Count characters between the cursor and the end of the current line."""
            remaining = 0
            idx = len(self.right) - 1
            # Because `self.right` is reversed, scanning backward from the end of `self.right`
            # walks forward in the document starting right after the cursor.
            while idx >= 0 and self.right[idx] != "\n":
                remaining += 1
                idx -= 1
            return remaining
    
        def _move_up(self) -> None:
            current_col = self._column()
            # If every character in `self.left` belongs to the current line, there is no '\n'
            # before the cursor, which means we are already on the first line.
            if current_col == len(self.left):
                return
    
            # Step left `current_col` times to reach column 0 of the current line,
            # plus 1 more step to cross the '\n' and land at the very end of the previous line.
            for _ in range(current_col + 1):
                self._step_left()
    
            # Since the cursor now sits at the end of the previous line, `_column()` equals its length.
            prev_line_len = self._column()
            target_col = min(current_col, prev_line_len)
            steps_from_line_end = prev_line_len - target_col
            for _ in range(steps_from_line_end):
                self._step_left()
    
        def _move_down(self) -> None:
            current_col = self._column()
            chars_to_line_end = self._rest_of_line()
            # If every character in `self.right` belongs to the current line, there is no '\n'
            # after the cursor, which means we are already on the last line.
            if chars_to_line_end == len(self.right):
                return
    
            # Step right `chars_to_line_end` times to reach the '\n' at the end of this line,
            # plus 1 more step to cross '\n' and land at column 0 of the next line.
            for _ in range(chars_to_line_end + 1):
                self._step_right()
    
            # Since the cursor now sits at column 0 of the next line, `_rest_of_line()` equals its length.
            next_line_len = self._rest_of_line()
            target_col = min(current_col, next_line_len)
            for _ in range(target_col):
                self._step_right()
    
    
    def run_text_editor(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]:
        editor = TextEditor()
        results: List[Optional[str]] = []
    
        # Replay each command in sequence; only "__str__" returns a string, while mutations return None.
        for op, args in zip(operations, arguments):
            if op == "type_in":
                editor.type_in(args[0])
                results.append(None)
            elif op == "backspace":
                editor.backspace()
                results.append(None)
            elif op == "move_cursor":
                editor.move_cursor(args[0])
                results.append(None)
            elif op == "__str__":
                results.append(str(editor))
            else:
                raise ValueError(f"unknown operation {op!r}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture splitting a deck of letter cards into two piles right where your cursor sits: a left pile facing up in reading order, and a right pile stored in reverse order so the very first character after the cursor rests right on top of the right pile. Each pile acts as a stack — a last-in, first-out list where elements are added or removed only at the top end (append and pop in Python). Because both characters immediately flanking the cursor sit at the top of a stack, typing, backspacing, and stepping horizontally only touch the tail of a Python list.

A naive design keeping a single Python string or a single character list plus an integer cursor slows down as the file grows. Python strings are immutable, so inserting one character copies all n characters in O(n) time, while inserting or deleting inside a single Python list shifts every trailing element by one slot (O(n) when editing near the top of a file). Splitting the document at the cursor avoids shifting trailing text altogether.

Trace Examples 2 and 3 in miniature: 1. Type "n", "e", "t": left = ['n', 'e', 't'], right = [] (renders "net|"). 2. move_cursor("left"): pop 't' from left onto right -> left = ['n', 'e'], right = ['t'] (renders "ne|t"). 3. type_in("x"): push 'x' onto left -> left = ['n', 'e', 'x'], right = ['t'] (renders "nex|t"). 4. For "up" on "sky\ns|ea" (left = ['s','k','y','\n','s'], right = ['a','e']), the cursor starts at column 1, steps left 1 + 1 = 2 times across 's' and '\n' to reach the end of "sky" (length 3), and steps left 3 - 1 = 2 more times to land at "s|ky\nsea".

Complexity

Let n be the current character count in the document, L_cur be the length of the cursor's line, and L_target be the length of the line moved onto:

  • type_in: O(1) amortized time per character. (Amortized O(1) means an operation takes constant time on average per call, even though Python occasionally resizes the underlying list array.) Each call simply appends to self.left.
  • backspace: O(1) time, popping the final element from self.left.
  • move_cursor("left") and move_cursor("right"): O(1) time, performing one pop() on one stack and one append() on the other.
  • move_cursor("up") and move_cursor("down"): O(L_cur + L_target) time, since scanning to the nearest "\n" and transferring characters across the cursor touches only the current line and the adjacent destination line.
  • __str__: O(n) time, walking every character in self.left and self.right once to build the (n + 1)-character return string.
  • Space: O(n), storing each document character once across self.left and self.right (plus O(n) temporary space when __str__ constructs its output).

Edge cases

  • Empty editor: str(TextEditor()) returns "|", and backspace plus all four move_cursor directions safely do nothing.
  • Backspace at offset 0 vs right after "\n": at offset 0, self.left is empty so nothing changes; right after "\n", popping "\n" joins the two lines.
  • Horizontal boundaries: "left" at offset 0 and "right" at the end of the text leave both stacks unchanged.
  • Clamping onto a shorter line: moving "up" or "down" from column 5 onto a 2-character line clamps to min(5, 2) = 2 (the end of that shorter line), and subsequent vertical moves measure from column 2.
  • Empty lines and trailing newlines: "ab\n" creates a zero-length second line after "\n", so "ab\n|" sits on line 1, column 0, and moving "up" lands at "|ab\n".
  • Top-line "up" and bottom-line "down": caught when _column() == len(self.left) or _rest_of_line() == len(self.right), leaving even a mid-line cursor untouched.

Common mistakes

  • Storing self.right in normal reading order: puts the character right after the cursor at self.right[0], turning every arrow-key move into an O(n) pop(0) / insert(0, ch).
  • Missing empty-stack checks: calling self.left.pop() on backspace() or "left" at offset 0 raises IndexError.
  • Off-by-one when crossing "\n" vertically: stepping left current_col times stops at column 0 of the current line (just after "\n"); current_col + 1 steps are required to cross "\n" onto the end of the preceding line.
  • Resetting to column 0 on top-line "up": moving characters before checking current_col == len(self.left) scrambles the cursor to index 0 instead of leaving it in place.
  • Concatenating with s += ch inside __str__: repeated string concatenation can take O(n^2) time; "".join(...) allocates the output in one O(n) pass.

Alternative approaches

  • Gap buffer: a gap buffer uses one contiguous character array with an unused [gap_start, gap_end) gap positioned at the cursor. Typing writes into gap_start, backspace widens the gap by 1, and horizontal steps copy one character across the gap — matching our two-stack asymptotics in a single flat array.
  • Array of per-line lists + (row, col): storing lines: List[List[str]] turns "up" and "down" into O(1) index updates, at the cost of O(line length) shifts on mid-line edits and O(num_lines) shifts when "\n" splits or joins lines.
  • Sticky (preferred_col) vertical movement: production editors record preferred_col on typing and horizontal moves, landing at min(preferred_col, target_line_len) on "up" / "down" so crossing a blank line restores your original column on the next long line.

Follow-up questions

  • How can you extend the editor with undo() and redo() operations covering character insertions and backspaces? Keep two stacks of edit tuples: undo_stack and redo_stack. When type_in inserts ch at document offset pos = len(self.left) - 1, push ("insert", ch, pos) onto undo_stack and clear redo_stack; when backspace() actually pops deleted_ch at pos = len(self.left), push ("delete", deleted_ch, pos) onto undo_stack and clear redo_stack (ignoring no-op backspaces at offset 0). Calling undo() pops the top record, moves the cursor to pos, applies the inverse edit, and pushes that record onto redo_stack; redo() pops redo_stack, re-applies the original edit, and pushes it back onto undo_stack.
  • Suppose files grow to tens of megabytes while the UI requests a rendered snapshot on every keystroke. How would you redesign rendering and storage? Local edits are already O(1), so the bottleneck is __str__ copying all n megabytes on every keypress. Replace full-document string serialization with a viewport query — a method returning only the 40–100 screen lines visible around the cursor — or emit small incremental change deltas (("insert", offset, ch)) so the UI patches only the edited line. Backing the document with a line-indexed tree lets the viewport slice lines [top_row, bottom_row] in O(log n + visible_chars) time without scanning from byte 0.
  • Compare a gap buffer, a rope, and an array of per-line buffers for this problem—what are the trade-offs and ideal workloads for each? A gap buffer (or our two-stack design) delivers O(1) local edits and horizontal steps with minimal memory overhead, making it great for single-cursor typing in small-to-medium files (GNU Emacs uses a gap buffer), though jumping to a distant mouse click slides the gap in O(distance) time. A rope — a balanced binary tree storing short string chunks in leaves and subtree character/newline counts in internal nodes — performs insertions, deletions, arbitrary offset jumps, and line lookups all in O(log n) time, suiting multi-megabyte files, multi-cursor editing, and persistent undo snapshots at higher implementation cost. An array of per-line buffers makes vertical moves and viewport slicing trivial, working nicely for lightweight viewers or modest files (especially when the active line uses its own gap buffer).

Follow-up questions

Similar questions

More Datologyai interview questions

All 3 Datologyai questions →