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: typetextat the cursor. The cursor ends up just after the typed text. Return the new cursor position.backspace(k: int) -> int: remove up tokcharacters immediately left of the cursor (fewer if the cursor is closer thankto the start). Return how many were removed.move_left(k: int) -> int/move_right(k: int) -> int: move the cursor up tokcharacters, 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
textholds printable ASCII characters and may be empty;0 <= k <= 10^6.- A document can grow to about
10^6characters, and there can be tens of thousands of calls, almost all of them small edits and moves near the cursor.
⭐ Bonus: a speed test on a large document earns a star if each insert, backspace and move costs time proportional to the characters it types, removes or moves over, not to the document's length. 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?