Skip to the code
+25 XP

#11 Text Cursor With a Sticky Column

medium

You're building a code editor. The document is lines, an array of strings. The cursor sits at [line, col], where col can be from 0 to the line's length (the spot after the last character). It starts at [0, 0]. The editor also remembers a preferred column, goal, which starts at 0.

keys is a string of these keys, handled in order:

  • L: if col > 0, move one left. Otherwise, if there is a line above, move to the end of that line. Then set goal = col.
  • R: if col is less than the line's length, move one right. Otherwise, if there is a line below, move to the start of that line. Then set goal = col.
  • U: if there is a line above, move up and set col to the smaller of goal and that line's length. On the first line, do nothing.
  • D: the same as U, but moving down. On the last line, do nothing.

Write editorCursor(lines, keys) that returns the final [line, col]. U and D never change goal, which is why the cursor returns to its old column after passing a short line.

Example 1

Input: lines = ["const a = 1;","","let b;"], keys = "RRRRDD"
Output: [2,4]

After four Rs, goal is 4. The empty line pulls col to 0, but the next line is long enough to get back to column 4.

Example 2

Input: lines = ["ab","cd"], keys = "RRR"
Output: [1,0]

At the end of "ab", R wraps to the start of the next line.

Constraints

  • 1 <= lines.length <= 1000
  • 0 <= lines[i].length <= 200
  • 0 <= keys.length <= 10^5
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).