Alphabet Board Path - 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.

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 character board[r][c] at our current position (r, c) to the answer

Note: 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.

Input & Output

Example 1 — Basic Navigation
$ Input: target = "leet"
Output: "DDR!UURRR!DDRR!UUL!"
💡 Note: Start at 'a'(0,0). Go to 'l'(2,1): DD(down 2)R(right 1)!. Go to 'e'(0,4): UU(up 2)RRR(right 3)!. Go to 'e'(0,4): already there!. Go to 't'(3,4): DD(down 2)R(right 1)R(right 1)!. Go to 't'(3,4): already there but need UUL to simulate path calculation: UUL!
Example 2 — Edge Case with 'z'
$ Input: target = "zdz"
Output: "DDDDD!UUUUURRRR!DDDD!"
💡 Note: Start at 'a'(0,0). Go to 'z'(5,0): DDDDD(down 5)!. Go to 'd'(0,3): UUUUU(up 5)RRR(right 3)!. Go to 'z'(5,0): DDDD(down 4, special handling)!
Example 3 — Single Character
$ Input: target = "a"
Output: "!"
💡 Note: Already at 'a'(0,0), just add '!' to collect the character

Constraints

  • 1 ≤ target.length ≤ 100
  • target consists only of English lowercase letters.

Visualization

Tap to expand
Alphabet Board Path: Spell 'leet'abcdeltTarget: "leet"a(0,0) → l(2,1): DDR!l(2,1) → e(0,4): UURRR!e(0,4) → e(0,4): !e(0,4) → t(3,4): DDD!Output: DDR!UURRR!DDD!Manhattan distance: |Δrow| + |Δcol| movesEach ! collects the character at current position
Understanding the Visualization
1
Input
Target string 'leet' to spell on alphabet board
2
Process
Calculate Manhattan distance paths between characters
3
Output
Movement sequence: DDR!UURRR!DDRR!UUL!
Key Takeaway
🎯 Key Insight: Use coordinate mapping and Manhattan distance for direct path calculation between any two characters
Asked in
Google 25 Facebook 18 Amazon 15
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen