Skip to main content
Back to problems
#1138
Medium Algorithms

Alphabet board path

Hash Table String
51.8% acceptance
Feb 25, 2026
935
187
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. (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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn alphabet_board_path(target: String) -> String {
    let pos = |c: u8| -> (i32, i32) {
      let idx = (c - b'a') as i32;
      (idx / 5, idx % 5)
    };
    let mut result = String::new();
    let (mut cr, mut cc) = (0i32, 0i32);
    for c in target.bytes() {
      let (tr, tc) = pos(c);
      // Move U/L first, then D/R to avoid going off board (z is at row 5 col 0)
      let dr = tr - cr;
      let dc = tc - cc;
      if dc < 0 { (0..(-dc)).for_each(|_| result.push('L')); }
      if dr < 0 { (0..(-dr)).for_each(|_| result.push('U')); }
      if dr > 0 { (0..dr).for_each(|_| result.push('D')); }
      if dc > 0 { (0..dc).for_each(|_| result.push('R')); }
      result.push('!');
      cr = tr; cc = tc;
    }
    result
  }
}