Problem Description
Design a text editor with a movable cursor that supports adding text, deleting text (like the backspace key), and moving the cursor left or right. Deletion only removes characters to the left of the cursor, and the cursor cannot move out of the bounds of the current text.
Key Insights
- Use two separate data structures (stacks) to represent the text to the left and right of the cursor.
- The left stack holds characters before the cursor, while the right stack holds characters after the cursor.
- Each operation is executed in O(k) time where k is the number of characters to process in that operation.
- Cursor movement is simulated by transferring characters between the left and right stacks.
- For retrieving the last min(10, len) characters left of the cursor, simply extract from the left stack.
Space and Time Complexity
Time Complexity: O(k) per call for addText, deleteText, cursorLeft, and cursorRight where k is the number of characters processed. Space Complexity: O(n) overall, where n is the total number of characters maintained in both stacks.
Solution
We simulate a text editor using two stacks. One stack, leftStack, contains characters to the left of the cursor; the other, rightStack, contains characters to the right. When adding text, push characters onto leftStack. For deleting text, pop characters from leftStack. Moving the cursor left pops characters from leftStack into rightStack (up to k times or until leftStack is empty), and moving right pops from rightStack back into leftStack. After each cursor move, the solution returns the last 10 characters from leftStack (or whatever is available). This approach guarantees that each operation processes only the relevant k characters.
Code Solutions
Below are code solutions in multiple languages.