Problem 248578 · medium · Phase 02 Linear Data Structures

Keystroke Editor With a Cursor

stacks · simulation · strings

Simulate a tiny text editor. keys is a list of keystrokes applied in order to an empty document whose cursor starts at position 0. Each keystroke is either a single character (inserted at the cursor, which then moves past it) or one of these commands:

  • "BS": delete the character just before the cursor (nothing if at the start);
  • "DEL": delete the character just after the cursor (nothing if at the end);
  • "LEFT" / "RIGHT": move the cursor one position (nothing if already at that edge).

Return the final document text.

Examples

Input:  keys = ["a", "b", "LEFT", "c", "BS", "d", "RIGHT", "e", "LEFT", "LEFT", "DEL"]
Output: "ade"
Explanation: "ab|" -> "a|b" -> "ac|b" -> "a|b" -> "ad|b" -> "adb|" -> "adbe|" -> "adb|e" -> "ad|be" -> "ad|e".

Input:  keys = ["BS", "LEFT", "x", "DEL", "RIGHT"]
Output: "x"

Constraints

  • 0 <= len(keys) <= 10**5
  • Single-character keys are printable and never equal to a command name
  • Target: O(n) time overall

Goals

  • Represent text around a cursor with two stacks
  • Move the cursor by transferring one character between the stacks
Starting Python…