Simulate a Cursor Editor with Sticky-Column Vertical Moves
Data Structure DesignAuto-graded · 19 test casesLast updated
Replay a log of editor commands (type, backspace, move in four directions, render) on a single-cursor multi-line buffer, with a column that persists across vertical moves.
You are given a recorded session for a small text editor. Replay it and report what the editor shows whenever it is asked to render.
The editor
The editor holds a sequence of text units and one cursor. The cursor sits in a gap between units, so it can take any position from 0 (before everything) to the number of units (after everything). The editor starts empty with the cursor at 0. There is no selection.
Input
operations: a list of command names.arguments: a list of the same length.arguments[i]is the list of arguments foroperations[i].
Each command is one of the following.
| Command | Arguments | Effect |
|---|---|---|
"init" | none | Reset to an empty editor with the cursor at 0. |
"type_in" | [unit] | Insert unit as one unit immediately before the cursor. The cursor then sits right after it. |
"backspace" | none | Remove the unit immediately before the cursor, and the cursor moves back by one. If the cursor is at position 0, nothing changes. |
"move_cursor" | [direction] | Move the cursor. direction is "left", "right", "up" or "down". |
"str" | none | Render the text with a ` |
Lines
A unit that is exactly the single newline character ("\n") is a line break. Every other unit is ordinary text, even if it looks like an escape sequence. Lines are the pieces of text separated by line breaks. The line break belongs to the end of its line, and the cursor directly after a line break is at column 0 of the next line. A line's length is the number of units in it, not counting its line break.
The column of the cursor is its distance from the start of the line it is on.
Movement rules
"left": move one unit left. At position0nothing happens. Moving left from the start of a line crosses the line break to the end of the previous line."right": move one unit right. At the very end nothing happens. Moving right at the end of a line crosses the line break to the start of the next line."up"/"down": move to the previous or next line. If there is no such line, the cursor stays where it is. Otherwise the cursor lands on the desired column of the target line, or at the end of the target line if the line is shorter than that.
Desired column
The desired column makes vertical movement remember where you started:
- When an
"up"or"down"command runs and no desired column is currently remembered, the desired column becomes the cursor's current column. This happens even if the move itself has no effect because there is no target line. - While a desired column is remembered, consecutive
"up"/"down"commands keep using it. The cursor may be clamped to a short line, but the desired column does not shrink. - Any
"type_in","backspace","left","right"or"init"command forgets the desired column. A"str"command does not.
Output
Return a list with one entry per command. The entry is the rendered string for "str" commands and None for all other commands. The rendered string is the units before the cursor, then |, then the units after the cursor, with line breaks left as they are.
Constraints
operationsandargumentshave equal length, at most a few thousand entries.- Every command name and direction is one of the values listed above.
"type_in"always has exactly one argument."move_cursor"always has exactly one argument.- The input contains no unknown commands.
Examples
Example 1
Input: run_editor_session(['init', 'type_in', 'type_in', 'type_in', 'str', 'backspace', 'str'], [[], ['a'], ['b'], ['c'], [], [], []])
Output: [None, None, None, None, 'abc|', None, 'ab|']
Example 2
Input: run_editor_session(['init', 'type_in', 'type_in', 'move_cursor', 'str', 'type_in', 'str', 'move_cursor', 'str'], [[], ['a'], ['b'], ['left'], [], ['x'], [], ['right'], []])
Output: [None, None, None, None, 'a|b', None, 'ax|b', None, 'axb|']
Example 3
Input: run_editor_session(['init', 'type_in', 'type_in', 'type_in', 'type_in', 'type_in', 'move_cursor', 'str'], [[], ['a'], ['b'], ['\\n'], ['c'], ['d'], ['up'], []])
Output: [None, None, None, None, None, None, None, 'ab\\ncd|']
Hints
Hint 1
Store the text as a list of units plus an integer cursor index. Typing is an insert at the index, backspace is a delete at index - 1, and rendering joins the two halves around a '|'.
Hint 2
For a vertical move, scan the text once to record where every line starts (index 0, and the index after each newline). Find the last start that is <= cursor to get the current line and column.
Hint 3
Keep a separate 'desired column' variable. Set it on the first up/down of a streak if it is empty, clear it on every other editing or horizontal command, and clamp to the target line's length when landing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the text as a Python list of units and the cursor as an integer index into the gaps between them. Process the commands in order and append one result per command.
- type_in: insert the unit at the cursor index and advance the cursor.
- backspace: if the cursor is above
0, delete the unit before it and step the cursor back. - left / right: clamp the cursor to
[0, len(units)]after moving by one. Newlines are ordinary units here, so crossing between lines needs no special handling. - str: join the units before the cursor, add
|, then join the rest. - up / down:
- Build the list of line start indices:
0plus the index after every newline unit. - The current line is the last start that is
<=the cursor, and the column is the cursor minus that start. - If no desired column is stored, store the current column.
- Pick the target line. If it does not exist, leave the cursor alone.
- Otherwise the target line's length is the next line start minus one minus its own start, or the end of the text for the last line. Place the cursor at the target start plus
min(desired_col, length).
- Build the list of line start indices:
- Every command except
strand a vertical move clears the desired column, which gives the "sticky column" behavior only across a run of vertical moves.
Why it is correct
The cursor index uniquely determines its line and column, because a line break belongs to the end of its line and the position directly after it is column 0 of the next line. Using the stored desired column rather than the current column means a clamp on a short line does not permanently lose the original column. Clearing it on edits and horizontal moves matches the rule that only an uninterrupted vertical streak is sticky. Clamping to the line length handles short and empty target lines, and doing nothing when there is no target line handles the first and last lines.
Complexity
Let n be the number of units and m the number of commands.
type_inandbackspacecost O(n) because of list shifting.leftandrightcost O(1), andstrcosts O(n).- A vertical move costs O(n) because of the line scan.
- Total time is O(m * n) in the worst case, and space is O(n).
Reference solution
from typing import List, Optional
def run_editor_session(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]:
units: List[str] = []
cursor = 0
desired_col = None
out: List[Optional[str]] = []
for op, args in zip(operations, arguments):
if op == "init":
units = []
cursor = 0
desired_col = None
out.append(None)
elif op == "type_in":
units.insert(cursor, args[0])
cursor += 1
desired_col = None
out.append(None)
elif op == "backspace":
if cursor > 0:
del units[cursor - 1]
cursor -= 1
desired_col = None
out.append(None)
elif op == "move_cursor":
direction = args[0]
if direction == "left":
cursor = max(0, cursor - 1)
desired_col = None
elif direction == "right":
cursor = min(len(units), cursor + 1)
desired_col = None
elif direction in ("up", "down"):
starts = [0]
for i, u in enumerate(units):
if u == "\n":
starts.append(i + 1)
line = 0
for i, s in enumerate(starts):
if s <= cursor:
line = i
else:
break
col = cursor - starts[line]
if desired_col is None:
desired_col = col
target = line + (-1 if direction == "up" else 1)
if 0 <= target < len(starts):
t_start = starts[target]
if target + 1 < len(starts):
t_end = starts[target + 1] - 1
else:
t_end = len(units)
cursor = t_start + min(desired_col, t_end - t_start)
else:
raise ValueError("invalid direction")
out.append(None)
elif op == "str":
out.append("".join(units[:cursor]) + "|" + "".join(units[cursor:]))
else:
raise ValueError("invalid operation")
return out