LeetCode solutions

1238. Alphabet Board Path

My accepted Python solution to LeetCode problem 1238, Alphabet Board Path, running in 33ms.

  • Difficulty: Medium
  • Python
  • Runtime 33ms
  • Memory 17.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 33ms, memory 17.2MB, accepted 2026-01-02.

python
class Solution:
    def alphabetBoardPath(self, target: str) -> str:
        result = []
        curr_row, curr_col = 0, 0
        
        for c in target:
            idx = ord(c) - ord('a')
            target_row, target_col = idx // 5, idx % 5
            
            # Move up/down first for 'z' edge case, move left before down
            if target_row < curr_row:
                result.append('U' * (curr_row - target_row))
            if target_col < curr_col:
                result.append('L' * (curr_col - target_col))
            if target_col > curr_col:
                result.append('R' * (target_col - curr_col))
            if target_row > curr_row:
                result.append('D' * (target_row - curr_row))
            
            result.append('!')
            curr_row, curr_col = target_row, target_col
        
        return ''.join(result)

Source