Multi-Line Buffer Editor with Four-Directional Cursor Navigation

Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Design an in-memory multi-line TextEditor that maintains an editable character sequence alongside a single insertion cursor, and expose it through the batch driver simulate_text_editor(operations, arguments).

A freshly initialized editor contains zero characters, with its cursor positioned at offset 0. Support the following behaviors:

  • init ([]): Discard any existing state and start over with an empty TextEditor instance. Return None.
  • type_in ([char]): Insert char directly to the left of the cursor so that the cursor remains immediately after the newly added character(s). Line breaks are entered as "\n". Return None.
  • backspace ([]): Erase the single character immediately preceding the cursor. When the cursor is already at offset 0, leave the buffer unchanged. Erasing a "\n" merges the current line onto the end of the preceding line. Return None.
  • move_cursor ([direction]): Relocate the cursor according to direction, then return None:
    • "left" / "right": Shift the cursor one character toward the beginning or end of the buffer (treating "\n" as a single character between adjacent lines). Stepping "left" at offset 0 or "right" past the final character has no effect.
    • "up" / "down": Jump to the line directly above or below the cursor's current line. Let col be the number of characters on the current line strictly before the cursor; place the cursor at column min(col, target_line_length) on the destination line, using the updated column on any subsequent vertical command. Calling "up" while on the top line or "down" while on the bottom line leaves the cursor unmoved.
  • str ([]): Render and return the full buffer as a string with "|" spliced in at the exact cursor location (preserving any "\n" characters as-is). An empty buffer renders as "|".

Given parallel lists operations and arguments, simulate_text_editor(operations, arguments) executes each command in order and returns the list of per-command results (None for mutating calls and the rendered string for "str").

Examples

Example 1

Input:
  operations = ["init", "type_in", "type_in", "type_in", "type_in", "str", "backspace", "str"]
  arguments  = [[], ["c"], ["o"], ["d"], ["e"], [], [], []]

Output:
  [None, None, None, None, None, "code|", None, "cod|"]

Explanation: After resetting the buffer, four insertions append 'c', 'o', 'd', and 'e' ahead of the cursor, producing "code|". One backspace removes 'e', leaving "cod|".

Example 2

Input:
  operations = ["init", "type_in", "type_in", "type_in", "move_cursor", "move_cursor", "str", "type_in", "str", "move_cursor", "str"]
  arguments  = [[], ["p"], ["n"], ["g"], ["left"], ["left"], [], ["i"], [], ["right"], []]

Output:
  [None, None, None, None, None, None, "p|ng", None, "pi|ng", None, "pin|g"]

Explanation: Typing "png" leaves "png|". Two "left" moves step across 'g' and 'n' to yield "p|ng". Inserting 'i' updates the buffer to "pi|ng", and one "right" move crosses 'n' to reach "pin|g".

Example 3

Input:
  operations = ["init", "type_in", "type_in", "type_in", "type_in", "type_in", "type_in", "type_in", "move_cursor", "str", "move_cursor", "str"]
  arguments  = [[], ["g"], ["o"], ["\n"], ["r"], ["u"], ["s"], ["t"], ["up"], [], ["down"], []]

Output:
  [None, None, None, None, None, None, None, None, None, "go|\nrust", None, "go\nru|st"]

Explanation: Typing "go\nrust" places the cursor at column 4 of the second line ("go\nrust|"). Moving "up" targets the two-character first line "go", clamping the column to min(4, 2) = 2 ("go|\nrust"). The subsequent "down" starts from column 2 and lands at min(2, 4) = 2 on the second line ("go\nru|st").

Constraints

  • 1 <= len(operations) == len(arguments) <= 10^5
  • Every entry in operations is one of "init", "type_in", "backspace", "move_cursor", or "str".
  • For "move_cursor", arguments[i][0] is one of "left", "right", "up", or "down".
  • There is only a single cursor and no text selection, and inserted text does not contain "|".
  • Single-character edits and horizontal cursor steps should run in $O(1)$ amortized time.

Step-by-step walkthrough

  1. Clarify boundary rules and the driver contract

    simulate_text_editor(operations, arguments) replays commands against an active TextEditor instance, appending str(editor) for "str" queries and None for "init", "type_in", "backspace", and "move_cursor".

    Before choosing a data structure, lock down every boundary behavior:

    • Buffer ends: backspace() and "left" at offset 0 are safe no-ops; "right" at the end of the buffer is a safe no-op.
    • Newlines ('\n'): '\n' is stored as an ordinary character. Stepping "left" from column 0 of line 2 crosses '\n' onto the end of line 1, and calling backspace() at column 0 of line 2 removes '\n' to join the two lines.
    • Vertical navigation ("up" / "down"): "up" on the top line and "down" on the bottom line leave the cursor untouched. Landing on a shorter line clamps the position to min(col, target_line_len), and the next vertical move measures from that clamped column.
  2. Why a flat string or single array is too slow

    Storing the buffer as a single Python str (or a single list of characters) alongside an integer cursor becomes costly whenever the cursor sits near the front of a 100,000-character file and a keystroke arrives:

    Single list:  ['p', 'i', 'n', 'g', ... 100,000 characters ...]
                         ^    ---> ---> ---> every element to the right shifts by 1!
    

    Slicing a Python string copies all n characters (O(n) per edit), and list.insert(cursor, ch) shifts all n - cursor trailing slots (O(n) worst case), even though edits only happen right beside the cursor.

  3. Part 1: Split the buffer into two stacks around the cursor

    Partition the characters directly at the cursor into two stacks (Python lists mutated exclusively via append and pop at the tail, both O(1)):

    • left: characters preceding the cursor in normal reading order (left[-1] sits immediately left of |).
    • right: characters following the cursor in reverse order (right[-1] sits immediately right of |).
    Buffer rendered as:   "p i | n g"
    
      left  (normal order):    ['p', 'i']    <- left[-1]  = 'i' (adjacent to '|')
      right (REVERSED order):  ['g', 'n']    <- right[-1] = 'n' (adjacent to '|')
    

    Keeping right reversed places the character right after the cursor ('n') at index -1 rather than index 0, making pushes and pops on both sides of | constant time:

    • type_in(ch): self.left.append(ch) — amortized O(1).
    • backspace(): self.left.pop() when self.left is non-empty — O(1).
    • __str__(): concatenate "".join(self.left), "|", and "".join(reversed(self.right)) — O(n).
    class TextEditor:
        def __init__(self) -> None:
            self.left: List[str] = []
            self.right: List[str] = []
    
        def type_in(self, char: str) -> None:
            for ch in char:
                self.left.append(ch)
    
        def backspace(self) -> None:
            if self.left:
                self.left.pop()
    
        def __str__(self) -> str:
            before_cursor = "".join(self.left)
            after_cursor = "".join(reversed(self.right))
            return before_cursor + "|" + after_cursor
    
  4. Part 2: Step left and right in O(1) time

    Because both stack tops face the cursor gap, horizontal movement transfers one character from one stack top to the other. Let's trace Example 2 ("png|"):

    After typing "png":     left = ['p', 'n', 'g'],  right = []          -> "png|"
    move_cursor("left"):    left = ['p', 'n'],       right = ['g']       -> "pn|g"
    move_cursor("left"):    left = ['p'],            right = ['g', 'n']  -> "p|ng"
    type_in("i"):           left = ['p', 'i'],       right = ['g', 'n']  -> "pi|ng"
    move_cursor("right"):   left = ['p', 'i', 'n'],  right = ['g']       -> "pin|g"
    

    When the source stack is empty (cursor already at either boundary), _step_left and _step_right safely do nothing:

        def _step_left(self) -> None:
            if self.left:
                self.right.append(self.left.pop())
    
        def _step_right(self) -> None:
            if self.right:
                self.left.append(self.right.pop())
    
  5. Part 3a: Measure the column offset and remaining line tail

    Vertical jumps need the cursor's offset within its current line:

    1. _column(): walk backward from self.left[-1] until hitting '\n' (or exhausting self.left). That count col is the cursor's zero-based column. Notice that when col == len(self.left), no '\n' precedes the cursor, proving it is already on the top line!
    2. _rest_of_line(): walk backward from self.right[-1] (advancing forward in reading order!) until hitting '\n' (or exhausting self.right). When rest == len(self.right), no '\n' follows the cursor, proving it is already on the bottom line!
        def _column(self) -> int:
            """Count characters on the current line strictly to the left of the cursor."""
            col = 0
            idx = len(self.left) - 1
            while idx >= 0 and self.left[idx] != "\n":
                col += 1
                idx -= 1
            return col
    
        def _rest_of_line(self) -> int:
            """Count characters on the current line strictly to the right of the cursor."""
            rest = 0
            idx = len(self.right) - 1
            while idx >= 0 and self.right[idx] != "\n":
                rest += 1
                idx -= 1
            return rest
    
  6. Part 3b: Jump up and down across uneven lines

    Trace Example 3 starting from "go\nrust|" (col = 4 on the second line):

    Start on line 1 (col = 4):    "go\nrust|"
      1) Step left col + 1 = 5 times (4 letters + '\n'):
         lands at END of line 0:  "go|\nrust"
      2) Measure prev_line_len = _column() = 2; target_col = min(4, 2) = 2.
      3) Step left prev_line_len - target_col = 2 - 2 = 0 times -> "go|\nrust".
    
    Now move down from "go|\nrust" (col = 2, rest = 0 on line 0):
      1) Step right rest + 1 = 1 time (crosses '\n'):
         lands at START of line 1: "go\n|rust"
      2) Measure next_line_len = _rest_of_line() = 4; target_col = min(2, 4) = 2.
      3) Step right target_col = 2 times -> "go\nru|st"!
    
        def _move_up(self) -> None:
            col = self._column()
            if col == len(self.left):
                return
    
            for _ in range(col + 1):
                self._step_left()
    
            prev_line_len = self._column()
            target_col = min(col, prev_line_len)
            for _ in range(prev_line_len - target_col):
                self._step_left()
    
        def _move_down(self) -> None:
            col = self._column()
            rest = self._rest_of_line()
            if rest == len(self.right):
                return
    
            for _ in range(rest + 1):
                self._step_right()
    
            next_line_len = self._rest_of_line()
            target_col = min(col, next_line_len)
            for _ in range(target_col):
                self._step_right()
    
  7. Wire up `move_cursor` and `simulate_text_editor`

    move_cursor dispatches the four valid directions to their helpers, and simulate_text_editor runs the command stream sequentially.

        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}")
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TextEditor:
        """Two-stack (gap-buffer style) text editor with four-way cursor movement."""
    
        def __init__(self) -> None:
            # left: chars before cursor in reading order; left[-1] is just before '|'.
            # Example for "pi|ng": left = ['p', 'i']
            self.left: List[str] = []
            # right: chars after cursor in REVERSE order; right[-1] is just after '|'.
            # Example for "pi|ng": right = ['g', 'n'] (reversed so pop/append are O(1))
            self.right: List[str] = []
    
        def type_in(self, char: str) -> None:
            # Insert each character right before the cursor (onto the top of `left`).
            # Iterating character-by-character also handles multi-character strings cleanly.
            for ch in char:
                self.left.append(ch)
    
        def backspace(self) -> None:
            # Guard against empty `left` so backspace at position 0 safely does nothing.
            if self.left:
                self.left.pop()
    
        def __str__(self) -> str:
            before_cursor = "".join(self.left)
            # Reverse `right` back into normal left-to-right reading order for display.
            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:
            # Move the character just before '|' across the cursor to sit just after '|'.
            if self.left:
                self.right.append(self.left.pop())
    
        def _step_right(self) -> None:
            # Move the character just after '|' across the cursor to sit just before '|'.
            if self.right:
                self.left.append(self.right.pop())
    
        def _column(self) -> int:
            """Count characters on the current line strictly to the left of the cursor."""
            col = 0
            idx = len(self.left) - 1
            while idx >= 0 and self.left[idx] != "\n":
                col += 1
                idx -= 1
            return col
    
        def _rest_of_line(self) -> int:
            """Count characters on the current line strictly to the right of the cursor."""
            rest = 0
            idx = len(self.right) - 1
            while idx >= 0 and self.right[idx] != "\n":
                rest += 1
                idx -= 1
            return rest
    
        def _move_up(self) -> None:
            col = self._column()
            # Why `col == len(self.left)`: if scanning back never hit '\n', the cursor
            # is already on the very first line, so moving up does nothing.
            if col == len(self.left):
                return
    
            # Why `col + 1`: cross the `col` chars on this line PLUS the '\n' before it,
            # landing at the very end of the previous line.
            for _ in range(col + 1):
                self._step_left()
    
            # At the end of the previous line, `_column()` equals that line's full length.
            prev_line_len = self._column()
            target_col = min(col, prev_line_len)
            for _ in range(prev_line_len - target_col):
                self._step_left()
    
        def _move_down(self) -> None:
            col = self._column()
            rest = self._rest_of_line()
            # Why `rest == len(self.right)`: if scanning forward never hit '\n', the cursor
            # is already on the very last line, so moving down does nothing.
            if rest == len(self.right):
                return
    
            # Why `rest + 1`: cross the remaining `rest` chars on this line PLUS its '\n',
            # landing at column 0 (the start) of the next line.
            for _ in range(rest + 1):
                self._step_right()
    
            # At the start of the next line, `_rest_of_line()` equals that line's full length.
            next_line_len = self._rest_of_line()
            target_col = min(col, next_line_len)
            for _ in range(target_col):
                self._step_right()
    
    
    def simulate_text_editor(
        operations: List[str],
        arguments: List[List[str]],
    ) -> List[Optional[str]]:
        # Replay operations against one TextEditor instance, resetting on "init".
        editor = TextEditor()
        results: List[Optional[str]] = []
    
        for op, args in zip(operations, arguments):
            if op == "init":
                editor = TextEditor()
                results.append(None)
            elif 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

Imagine holding a row of letter tiles split between your left hand and your right hand, with the cursor | sitting right in the gap between your two thumbs. Each hand acts as a stack — a last-in, first-out list where items are added or removed only at the very end (append and pop). Your left stack holds all characters preceding the cursor in reading order (['p', 'i']), while your right stack holds all characters following the cursor in reverse order (['g', 'n'] for "pi|ng") so the character immediately right of the cursor ('n') sits on top of the right stack. Inserting appends to left, backspace pops left, stepping horizontally transfers one tile between stack tops, and jumping vertically steps across the dividing '\n' onto the adjacent line to land at min(current_column, target_line_length).

A naive design keeps the buffer as a single Python str (or a single list of characters) plus an integer cursor. Because Python strings are immutable, text[:cursor] + ch + text[cursor:] copies all n characters on every keystroke (O(n)), and list.insert(cursor, ch) shifts up to n trailing elements whenever edits occur near the front of a long file. Splitting directly at the cursor ensures local edits and horizontal steps never touch distant characters.

Trace Example 2 ("p", "n", "g", left, left, "i", right): 1. type_in('p'), type_in('n'), type_in('g'): left = ['p', 'n', 'g'], right = [] ("png|"). 2. Two move_cursor('left') calls: pop 'g' then 'n' onto right -> left = ['p'], right = ['g', 'n'] ("p|ng"). 3. type_in('i'): append 'i' to left -> left = ['p', 'i'], right = ['g', 'n'] ("pi|ng"). 4. move_cursor('right') and str(): pop 'n' from right back onto left -> "pin|g".

Complexity

Let n be the current character count in the buffer, L_cur be the length of the cursor's line, and L_target be the length of the destination line during a vertical move.

  • type_in(char): amortized O(1) per character (an occasional underlying array resize copies elements, while the average cost per append across any sequence of operations stays constant), since each character executes one self.left.append(ch).
  • backspace(): O(1) time, popping the final slot of self.left with zero element shifts.
  • move_cursor("left" / "right"): O(1) time, performing one pop() on one stack and one append() on the other.
  • move_cursor("up" / "down"): O(L_cur + L_target) time, because _column() and _rest_of_line() stop at the nearest '\n' on the current and destination lines, stepping across at most L_cur + 1 + L_target characters regardless of total document size n.
  • __str__(): O(n) time, visiting each stored character once to assemble the (n + 1)-character result string.
  • Space: O(n) total memory across self.left and self.right, storing each character in the buffer once.

Edge cases

  • Empty buffer: left = [] and right = [], so str(editor) produces "|", and backspace or any move_cursor call is a safe no-op.
  • Boundaries at index 0 and buffer end: if self.left: and if self.right: guard every pop() against IndexError.
  • Backspace at column 0 of line 2+: self.left[-1] is '\n', so popping it deletes the line break and joins the current line onto the previous one.
  • Clamping onto a shorter line ("go\nrust|" -> "up" -> "down"): min(col, prev_line_len) clamps column 4 down to 2 ("go|\nrust"), and moving "down" next measures from column 2 to land at "go\nru|st".
  • Empty lines ("a\n\nbc"): two adjacent '\n' characters bound a zero-length line, so min(col, 0) places the cursor cleanly at column 0 ("a\n|\nbc").
  • Up on the top line / down on the bottom line: col == len(self.left) and rest == len(self.right) return immediately without moving the cursor.

Common mistakes

  • Keeping right in left-to-right reading order: then the character immediately after | sits at right[0], turning "left" and "right" into O(n) insert(0, ...) / pop(0) calls.
  • Omitting reversed(self.right) in __str__: prints everything after the cursor backwards ("pi|gn" instead of "pi|ng").
  • Stepping col times instead of col + 1 in _move_up (or rest instead of rest + 1 in _move_down): col steps stop at column 0 of the current line with '\n' still sitting in self.left[-1], one step short of crossing onto the line above.
  • Measuring _column() after moving the cursor: col must be captured before crossing '\n', because afterward _column() measures the destination line's length instead.
  • Snapping to offset 0 on "up" from the first line: jumping to column 0 on top-line "up" violates the boundary rule that out-of-range vertical moves leave a mid-line cursor unchanged.

Alternative approaches

  • Gap buffer: a gap buffer stores one flat character array containing a contiguous [gap_start, gap_end) span of unused slots at the cursor. It mirrors our two-stack mechanics inside a single allocation, lowering pointer overhead in systems languages like C or Rust.
  • Per-line array + (row, col) coordinates: maintaining lines: List[List[str]] turns vertical jumps into O(1) row arithmetic, at the cost of splitting and concatenating line arrays whenever '\n' is inserted or deleted.
  • Rope: a rope is a balanced binary tree whose leaves hold short string chunks and whose internal nodes cache subtree character and newline counts, giving O(log n) edits and O(log n) arbitrary jumps on multi-megabyte documents at higher code complexity.

Follow-up questions

  • How would you support undo() and redo() across character insertions and deletions, including what metadata each history entry stores and how fresh edits affect the redo stack? Maintain an undo_stack and a redo_stack of (kind, char, offset) records, where offset = len(self.left) right before the mutation (("insert", ch, offset) on type_in, and ("delete", erased_ch, offset - 1) whenever backspace actually removes a character). Calling undo() pops undo_stack, steps the cursor to offset (which takes O(1) when undoing at the active cursor and O(|cursor - offset|) otherwise), applies the inverse mutation, and pushes the record onto redo_stack; redo() pops redo_stack, replays the edit, and pushes it back onto undo_stack. Any fresh type_in or non-empty backspace must call redo_stack.clear() so stale timeline branches can never be replayed out of context.
  • When lines contain tens of thousands of characters, scanning to \n makes vertical cursor jumps costly. How can you make up/down navigation independent of line width while keeping keystrokes O(1)? Give every line its own two-stack LineBuffer (storing left, right, and total length len(left) + len(right)), hold the lines in a list or balanced tree, and track (row, col) explicitly. Then "up" and "down" adjust row by -1 or +1 and clamp col = min(col, target_line.length) in O(1) time without transferring any characters yet, while a LineBuffer shifts its internal gap to col lazily only when an edit or horizontal move actually happens on that line (keeping consecutive typing keystrokes O(1)). If documents also have millions of lines so '\n' splits/merges cannot afford O(num_lines) list shifts, store the line buffers in a balanced tree (or rope) for O(log num_lines) vertical jumps and line edits.
  • Suppose you need word-level cursor jumps to the beginning of the preceding or following word. How do you define word boundaries, and how does the implementation build on your existing primitives? Define word characters via a predicate like is_word(ch) = ch.isalnum() or ch == "_", treating whitespace, punctuation, and '\n' as delimiters, and compose two loops directly over _step_left and _step_right with zero changes to left and right. Jumping to the preceding word's start first skips delimiter characters (while self.left and not is_word(self.left[-1]): self._step_left()) and then steps across the word's characters (while self.left and is_word(self.left[-1]): self._step_left()); jumping to the following word's start steps right past any remaining characters of the current word and then past delimiters, running in O(skipped characters) time.

Follow-up questions

Similar questions

More Datologyai interview questions

All 3 Datologyai questions →