Problem
On an alphabet board, we start at position (0, 0)
, corresponding to character board[0][0]
.
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
, as shown in the diagram below.
$$ \begin{bmatrix} a & b & c & d & e \\ f & g & h & i & j \\ k & l & m & n & o \\ p & q & r & s & 6 \\ u & v & w & x & y \\ z \end{bmatrix} $$
We may make the following moves:
'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the characterboard[r][c]
at our current position(r, c)
to the answer.
(Here, the only positions that exist on the board are positions with letters on them.)
Return a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.
Solution
Method 1 – Greedy Path Construction
Intuition
The key idea is to always move from the current character’s position to the next target character’s position using the shortest valid path, taking care with the special case of ‘z’, which is alone in the last row. By always moving up/left before down/right when necessary, we avoid invalid board positions.
Approach
- Map Characters to Board Positions:
- Build a mapping from each letter to its (row, col) position on the board.
- Iterate Over Target String:
- Start at (0, 0).
- For each character in
target
:- Find its (row, col) position.
- Move vertically (up or down) to the target row.
- Move horizontally (left or right) to the target column.
- Append ‘!’ to select the character.
- Update the current position.
- Handle ‘z’ Carefully:
- Always move up before right when moving to ‘z’, and left before down when moving away from ‘z’, to avoid invalid positions.
- Build and Return the Resulting Path.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
, whereN
is the length oftarget
. - 🧺 Space complexity:
O(1)
(ignoring output), as the board and mapping are constant size.