Skip to the code
cf.
+10 XP

#10 Keyboard Cursor on a Canvas

easy

A pixel-art editor lets you move the selected cell with arrow keys. The canvas is width cells wide and height cells tall; columns count from 0 on the left and rows from 0 at the top. The cursor starts at start, given as [x, y] (column, row).

keys is a string of U, D, L, and R: up (row - 1), down (row + 1), left (column - 1), and right (column + 1). A key that would move the cursor off the canvas does nothing.

Write moveCursor(width, height, start, keys) that returns the final [x, y].

Example 1

Input: width = 3, height = 3, start = [0,0], keys = "RRRDDL"
Output: [1,2]

The third R would leave the canvas, so it is ignored. Then down, down, left.

Example 2

Input: width = 4, height = 2, start = [3,1], keys = "DDRU"
Output: [3,0]

Both D keys and the R would leave the canvas; only U moves.

Constraints

  • 1 <= width, height <= 1000
  • start is on the canvas.
  • 0 <= keys.length <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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