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]): Placechardirectly ahead of the cursor, advancing the cursor so it sits immediately afterchar. Line breaks are typed as"\n". AppendsNoneto the output list.backspace([]): Remove the character directly to the left of the cursor. Callingbackspacewhen the cursor is at index0makes no change; removing a"\n"fuses the current line onto the tail of the line above it. AppendsNoneto the output list.move_cursor([direction]): Reposition the cursor based ondirectionand appendNoneto 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 index0or at the end of the document."up"and"down"move to the preceding or following"\n"-delimited line. Withcoldenoting the number of characters before the cursor on its current line, the cursor lands at offsetmin(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__([]): Appendstr(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
Pin down the document rules first
run_text_editor(operations, arguments)executes commands on a freshTextEditor. Mutating methods ("type_in","backspace","move_cursor") produceNone, while"__str__"producesstr(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 index0leave 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, andbackspace()immediately after"\n"removes the newline to fuse the two lines. - Vertical navigation (
"up"and"down"): preserve the cursor's current columncol, or clamp tomin(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 line0or"down"on the final line is a no-op.
- Initial state: an empty document places the cursor at index
Why a single string or single list falls short
Keeping the document as a Python
strplus an integercursorcopies 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 + 1Even a single Python
listof characters withchars.insert(cursor, ch)andchars.pop(cursor - 1)shifts every character aftercursorby 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.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 index0).
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_inappends ontoself.left,backspacepopsself.left, and__str__concatenatesself.left,"|", andreversed(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_cursorPart 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 ontoself.right. - Step right: pop
self.right[-1]and append it ontoself.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)- Step left: pop
Part 3: Measuring columns and jumping up or down
Vertical navigation relies on two local measurements around the cursor:
_column(): count characters backward fromself.left[-1]up to the nearest"\n"(or start of text)._rest_of_line(): count characters backward fromself.right[-1]up to the nearest"\n"(or end of text). Becauseself.rightis reversed, walking backward fromself.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 line0— return early. - Otherwise, step leftcurrent_col + 1times to cross thecurrent_colcharacters on this line plus the preceding"\n", landing at the very end of the line above. - Measureprev_line_len = self._column(), computetarget_col = min(current_col, prev_line_len), and step leftprev_line_len - target_coladditional 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 rightchars_to_line_end + 1times to reach column0of the next line, readnext_line_len = self._rest_of_line(), and step rightmin(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()Connect `move_cursor` and `run_text_editor`
move_cursorroutes"left","right","up", and"down"to the four helpers, andrun_text_editorreplays the command list on oneTextEditorinstance: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 resultsComplete 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 toself.left.backspace: O(1) time, popping the final element fromself.left.move_cursor("left")andmove_cursor("right"): O(1) time, performing onepop()on one stack and oneappend()on the other.move_cursor("up")andmove_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 inself.leftandself.rightonce to build the(n + 1)-character return string.- Space: O(n), storing each document character once across
self.leftandself.right(plusO(n)temporary space when__str__constructs its output).
Edge cases
- Empty editor:
str(TextEditor())returns"|", andbackspaceplus all fourmove_cursordirections safely do nothing. - Backspace at offset 0 vs right after
"\n": at offset0,self.leftis empty so nothing changes; right after"\n", popping"\n"joins the two lines. - Horizontal boundaries:
"left"at offset0and"right"at the end of the text leave both stacks unchanged. - Clamping onto a shorter line: moving
"up"or"down"from column5onto a 2-character line clamps tomin(5, 2) = 2(the end of that shorter line), and subsequent vertical moves measure from column2. - Empty lines and trailing newlines:
"ab\n"creates a zero-length second line after"\n", so"ab\n|"sits on line1, column0, 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.rightin normal reading order: puts the character right after the cursor atself.right[0], turning every arrow-key move into anO(n)pop(0)/insert(0, ch). - Missing empty-stack checks: calling
self.left.pop()onbackspace()or"left"at offset0raisesIndexError. - Off-by-one when crossing
"\n"vertically: stepping leftcurrent_coltimes stops at column0of the current line (just after"\n");current_col + 1steps are required to cross"\n"onto the end of the preceding line. - Resetting to column 0 on top-line
"up": moving characters before checkingcurrent_col == len(self.left)scrambles the cursor to index0instead of leaving it in place. - Concatenating with
s += chinside__str__: repeated string concatenation can takeO(n^2)time;"".join(...)allocates the output in oneO(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 intogap_start, backspace widens the gap by1, 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): storinglines: List[List[str]]turns"up"and"down"intoO(1)index updates, at the cost ofO(line length)shifts on mid-line edits andO(num_lines)shifts when"\n"splits or joins lines. - Sticky (
preferred_col) vertical movement: production editors recordpreferred_colon typing and horizontal moves, landing atmin(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()andredo()operations covering character insertions and backspaces? Keep two stacks of edit tuples:undo_stackandredo_stack. Whentype_ininsertschat document offsetpos = len(self.left) - 1, push("insert", ch, pos)ontoundo_stackand clearredo_stack; whenbackspace()actually popsdeleted_chatpos = len(self.left), push("delete", deleted_ch, pos)ontoundo_stackand clearredo_stack(ignoring no-op backspaces at offset0). Callingundo()pops the top record, moves the cursor topos, applies the inverse edit, and pushes that record ontoredo_stack;redo()popsredo_stack, re-applies the original edit, and pushes it back ontoundo_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 allnmegabytes 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]inO(log n + visible_chars)time without scanning from byte0. - 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 inO(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 inO(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
- How can you extend the editor with `undo()` and `redo()` operations covering character insertions and backspaces?
- Suppose files grow to tens of megabytes while the UI requests a rendered snapshot on every keystroke. How would you redesign rendering and storage?
- 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?
Similar questions
- Multi-Line Buffer Editor with Four-Directional Cursor Navigation
- 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