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 emptyTextEditorinstance. ReturnNone.type_in([char]): Insertchardirectly to the left of the cursor so that the cursor remains immediately after the newly added character(s). Line breaks are entered as"\n". ReturnNone.backspace([]): Erase the single character immediately preceding the cursor. When the cursor is already at offset0, leave the buffer unchanged. Erasing a"\n"merges the current line onto the end of the preceding line. ReturnNone.move_cursor([direction]): Relocate the cursor according todirection, then returnNone:"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 offset0or"right"past the final character has no effect."up"/"down": Jump to the line directly above or below the cursor's current line. Letcolbe the number of characters on the current line strictly before the cursor; place the cursor at columnmin(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
operationsis 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
Clarify boundary rules and the driver contract
simulate_text_editor(operations, arguments)replays commands against an activeTextEditorinstance, appendingstr(editor)for"str"queries andNonefor"init","type_in","backspace", and"move_cursor".Before choosing a data structure, lock down every boundary behavior:
- Buffer ends:
backspace()and"left"at offset0are 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 column0of line 2 crosses'\n'onto the end of line 1, and callingbackspace()at column0of 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 tomin(col, target_line_len), and the next vertical move measures from that clamped column.
- Buffer ends:
Why a flat string or single array is too slow
Storing the buffer as a single Python
str(or a singlelistof characters) alongside an integercursorbecomes 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
ncharacters (O(n)per edit), andlist.insert(cursor, ch)shifts alln - cursortrailing slots (O(n)worst case), even though edits only happen right beside the cursor.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
appendandpopat the tail, bothO(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
rightreversed places the character right after the cursor ('n') at index-1rather than index0, making pushes and pops on both sides of|constant time:type_in(ch):self.left.append(ch)— amortizedO(1).backspace():self.left.pop()whenself.leftis 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_cursorPart 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_leftand_step_rightsafely 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())Part 3a: Measure the column offset and remaining line tail
Vertical jumps need the cursor's offset within its current line:
_column(): walk backward fromself.left[-1]until hitting'\n'(or exhaustingself.left). That countcolis the cursor's zero-based column. Notice that whencol == len(self.left), no'\n'precedes the cursor, proving it is already on the top line!_rest_of_line(): walk backward fromself.right[-1](advancing forward in reading order!) until hitting'\n'(or exhaustingself.right). Whenrest == 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 restPart 3b: Jump up and down across uneven lines
Trace Example 3 starting from
"go\nrust|"(col = 4on 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()Wire up `move_cursor` and `simulate_text_editor`
move_cursordispatches the four valid directions to their helpers, andsimulate_text_editorruns 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}")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 oneself.left.append(ch).backspace(): O(1) time, popping the final slot ofself.leftwith zero element shifts.move_cursor("left" / "right"): O(1) time, performing onepop()on one stack and oneappend()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 mostL_cur + 1 + L_targetcharacters regardless of total document sizen.__str__(): O(n) time, visiting each stored character once to assemble the(n + 1)-character result string.- Space: O(n) total memory across
self.leftandself.right, storing each character in the buffer once.
Edge cases
- Empty buffer:
left = []andright = [], sostr(editor)produces"|", andbackspaceor anymove_cursorcall is a safe no-op. - Boundaries at index 0 and buffer end:
if self.left:andif self.right:guard everypop()againstIndexError. - 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 column4down to2("go|\nrust"), and moving"down"next measures from column2to land at"go\nru|st". - Empty lines (
"a\n\nbc"): two adjacent'\n'characters bound a zero-length line, somin(col, 0)places the cursor cleanly at column0("a\n|\nbc"). - Up on the top line / down on the bottom line:
col == len(self.left)andrest == len(self.right)return immediately without moving the cursor.
Common mistakes
- Keeping
rightin left-to-right reading order: then the character immediately after|sits atright[0], turning"left"and"right"intoO(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
coltimes instead ofcol + 1in_move_up(orrestinstead ofrest + 1in_move_down):colsteps stop at column0of the current line with'\n'still sitting inself.left[-1], one step short of crossing onto the line above. - Measuring
_column()after moving the cursor:colmust be captured before crossing'\n', because afterward_column()measures the destination line's length instead. - Snapping to offset
0on"up"from the first line: jumping to column0on 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: maintaininglines: List[List[str]]turns vertical jumps intoO(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 andO(log n)arbitrary jumps on multi-megabyte documents at higher code complexity.
Follow-up questions
- How would you support
undo()andredo()across character insertions and deletions, including what metadata each history entry stores and how fresh edits affect the redo stack? Maintain anundo_stackand aredo_stackof(kind, char, offset)records, whereoffset = len(self.left)right before the mutation (("insert", ch, offset)ontype_in, and("delete", erased_ch, offset - 1)wheneverbackspaceactually removes a character). Callingundo()popsundo_stack, steps the cursor tooffset(which takesO(1)when undoing at the active cursor andO(|cursor - offset|)otherwise), applies the inverse mutation, and pushes the record ontoredo_stack;redo()popsredo_stack, replays the edit, and pushes it back ontoundo_stack. Any freshtype_inor non-emptybackspacemust callredo_stack.clear()so stale timeline branches can never be replayed out of context. - When lines contain tens of thousands of characters, scanning to
\nmakes 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-stackLineBuffer(storingleft,right, and total lengthlen(left) + len(right)), hold the lines in a list or balanced tree, and track(row, col)explicitly. Then"up"and"down"adjustrowby-1or+1and clampcol = min(col, target_line.length)in O(1) time without transferring any characters yet, while aLineBuffershifts its internal gap tocollazily only when an edit or horizontal move actually happens on that line (keeping consecutive typing keystrokesO(1)). If documents also have millions of lines so'\n'splits/merges cannot affordO(num_lines)list shifts, store the line buffers in a balanced tree (or rope) forO(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_leftand_step_rightwith zero changes toleftandright. 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 inO(skipped characters)time.
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?
- 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)?
- 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?
Similar questions
- Stateful Document Cursor with Typing, Deletion, and 2D Movement
- Word Frequencies and Bag Intersection on a Minimal RDD
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging