~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

OA: Text editor with a clipboard, undo and several documents

hard 4 levels ~90 min

Level 1 Typing and moving the cursor

You're building the editing core of a small text editor. Implement TextEditor. It starts with an empty document and the cursor at position 0. Positions count characters: position p is the gap just before character p (so 0 is the very start and len(text) the very end).

  • insert(text: str) -> int: type text at the cursor. The cursor ends up just after the typed text. Return the new cursor position.
  • backspace(k: int) -> int: remove up to k characters immediately left of the cursor (fewer if the cursor is closer than k to the start). Return how many were removed.
  • move_left(k: int) -> int / move_right(k: int) -> int: move the cursor up to k characters, stopping at either end of the text. Return the new position.
  • get_text() -> str: the whole document.
ed = TextEditor()
ed.insert("hello world")   # 11
ed.move_left(6)            # 5   just after "hello"
ed.insert(",")             # 6
ed.get_text()              # "hello, world"
ed.backspace(3)            # 3   removes "lo,"
ed.get_text()              # "hel world"
ed.move_right(100)         # 9   stops at the end
ed.backspace(0)            # 0

Constraints

  • text holds printable ASCII characters and may be empty; 0 <= k <= 10^6.
  • A document can grow to about 10^6 characters, and there can be tens of thousands of calls, almost all of them small edits and moves near the cursor.

Aim for each insert, backspace and move to cost time proportional to the characters it types, removes or moves over, not to the length of the document. get_text may take O(n); it's called rarely.

Show hint

Real editors keep the text split at the cursor. What if the characters before the cursor and the characters after it lived in two separate stacks?

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Level 4 unlocks when level 3 passes.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

0:00
Ctrl ' run · Ctrl ↵ submit
esc