Two-Stack Document Editor with Cursor Operations
Data Structure DesignAuto-graded · 16 test casesLast updated
Tests efficient implementation of a mutable text buffer with insertion, deletion, and bidirectional cursor movement using dual-stack architecture.
Build an in-memory text buffer that tracks a movable cursor position. The buffer begins empty with the cursor at the start.
Your task is to process a sequence of operations on this buffer. You'll receive two parallel lists: operations containing operation names, and arguments containing the parameters for each operation.
Implement a function that handles these operations:
"TextEditor": Reset the buffer to empty and place the cursor at position 0. ReturnNone."insert": Add the stringtextat the cursor's current location. The cursor advances to immediately after the inserted text. ReturnNone."delete": Remove up tokcharacters that appear directly before the cursor. The cursor moves backward by the number of characters actually removed. Return the count of deleted characters as an integer."cursor_left": Shift the cursorkpositions toward the start of the buffer, but stop if it reaches position 0. Return a string containing up to 10 characters immediately before the cursor's new position (or fewer if fewer exist)."cursor_right": Shift the cursorkpositions toward the end of the buffer, but stop if it reaches the final position. Return a string containing up to 10 characters immediately before the cursor's new position (or fewer if fewer exist).
The function must return a list where each element corresponds to the result of the operation at that index.
Constraints
- Each
"insert"operation provides a string of length 1 to 40 - Each
"delete","cursor_left", and"cursor_right"operation has1 ≤ k ≤ 40 - All inserted text contains only lowercase English letters
- The total number of operations across all method calls will not exceed
2 × 10⁵ - Your implementation must handle the full workload efficiently without quadratic time complexity
Examples
Example 1
Input: process_text_editor(['TextEditor', 'insert', 'delete', 'insert', 'cursor_left', 'cursor_right', 'delete'], [[], ['hello'], [2], ['p'], [2], [1], [10]])
Output: [None, None, 2, None, 'he', 'hel', 3]
Hints
Hint 1
Think about what data structure allows O(1) insertion and deletion at one specific location while avoiding expensive shifts of other elements.
Hint 2
Consider splitting the buffer into two parts at the cursor position, where each part supports efficient operations at its boundary.
Hint 3
When moving the cursor, characters cross from one partition to the other—make sure to preserve their relative order in the document.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is supporting fast edits at an arbitrary cursor position without repeatedly shifting characters. A naive approach using a single string would require O(n) time per insertion or deletion in the middle of the document.
The solution uses two stacks that partition the buffer at the cursor:
left: holds all characters before the cursor, stored in document order with the rightmost character (closest to cursor) at the endright: holds all characters after the cursor, stored in reverse document order with the leftmost character (closest to cursor) at the end
This organization ensures all operations touch only the ends of these lists, which Python handles in amortized O(1) time per element.
Operation implementations:
-
Insert: Append each character of the input string to
left. The cursor naturally ends up after the new text. -
Delete: Remove up to
kcharacters from the end ofleft(the characters immediately before the cursor). Clamp to the actual length ofleftand return the count. Special care:del left[-0:]would incorrectly clear the entire list, so only delete when count is positive. -
Cursor left: Move the last
countcharacters fromlefttoright. Sincerightstores characters in reverse order, we reverse the slice before extending. Remove those characters fromleft. Return the last 10 characters of the updatedleft. -
Cursor right: Move the last
countcharacters fromrighttoleft. Reverse them back to document order before appending. Return the last 10 characters of the updatedleft. -
TextEditor: Clear both stacks to reset state.
Why it works: The invariant is that the complete document equals left + reversed(right), and the cursor position is always len(left). Each operation preserves this invariant while only modifying stack ends.
Complexity
-
Time: Each character operation (insert character, delete character, move character) costs O(1) amortized. Since parameters are bounded by 40, each operation call is effectively O(1). Over all operations, the total time is O(total characters processed), which is linear in the input size with no quadratic degradation.
-
Space: O(n) where n is the maximum document length across all operations. Each character exists in exactly one stack.
Solution Code
from typing import List, Optional
def process_text_editor(operations: List[str], arguments: List[List]) -> List[Optional[object]]:
left = []
right = []
results = []
for operation, args in zip(operations, arguments):
if operation == "TextEditor":
left.clear()
right.clear()
results.append(None)
elif operation == "insert":
left.extend(args[0])
results.append(None)
elif operation == "delete":
count = min(args[0], len(left))
if count:
del left[-count:]
results.append(count)
elif operation == "cursor_left":
count = min(args[0], len(left))
if count:
right.extend(reversed(left[-count:]))
del left[-count:]
results.append("".join(left[-10:]))
elif operation == "cursor_right":
count = min(args[0], len(right))
if count:
left.extend(reversed(right[-count:]))
del right[-count:]
results.append("".join(left[-10:]))
return results