Text Editor Cursor
Medium · design
A small text editor starts with empty text and a blinking cursor. The cursor sits between two characters (or at either end of the text), and it begins at position 0. You are given a list of commands, run in order. Each command is a name, one space, and an argument:
"insert <text>": put<text>into the text exactly where the cursor is. The cursor ends up just after the inserted text, so the text that was to the right of the cursor stays to its right."delete <k>": remove thekcharacters just to the left of the cursor, or all of them if there are fewer thank. Characters to the right of the cursor are not touched, and the cursor stays between the same two characters as before."left <k>": move the cursorkcharacters to the left, or as far as the start of the text if there are fewer thank. The text does not change."right <k>": move the cursorkcharacters to the right, or as far as the end of the text if there are fewer thank. The text does not change."look <k>": record the up tokcharacters just to the left of the cursor, in their order in the text. If there are none, record the empty string. The text and the cursor do not change.
Return a list with everything recorded by the "look" commands, in the order the commands were given.
Examples
Example 1
Input: commands = ["insert hello", "left 2", "insert xy", "look 6"]
Output: ["helxy"]
After hello, two steps left put the cursor between hel and lo. The text becomes helxylo with the cursor after xy, so the five characters to its left are all there is.
Example 2
Input: commands = ["insert abc", "delete 2", "look 5", "left 5", "delete 1", "right 9", "insert z", "look 3"]
Output: ["a", "az"]
Deleting two leaves a. The cursor goes to the start, where there is nothing to delete, then to the end after the a. Inserting z there gives az.
Example 3
Input: commands = ["look 3", "insert go", "left 1", "look 3", "right 1", "look 1"]
Output: ["", "g", "o"]
The first look finds an empty text. With the cursor between g and o, only g is on its left. After moving right, the last character on its left is o.
Constraints
- 1 <= len(commands) <= 10^4
- Every command is one of the five above, with exactly one space between the name and the argument.
- <text> has 1 to 20 lowercase letters.
- For delete, left, right and look, k is an integer with 1 <= k <= 20.
- At least one command is a look.