KatInterview

Two-Stack Document Editor with Cursor Operations

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designstacksstring-manipulationsimulation

Last 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. Return None.
  • "insert": Add the string text at the cursor's current location. The cursor advances to immediately after the inserted text. Return None.
  • "delete": Remove up to k characters 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 cursor k positions 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 cursor k positions 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 has 1 ≤ 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.