#1138

Alphabet Board Path

Medium
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution improves efficiency by reducing unnecessary moves. Instead of moving in a straight line to each character, we can calculate the direction to move in a single pass, minimizing the number of moves.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a mapping of each character to its position on the board.
  2. 2Step 2: For each character in the target string, determine the target position and calculate the difference in rows and columns from the current position.
  3. 3Step 3: Move vertically and horizontally based on the calculated differences, appending the necessary moves to the result string.
solution.py20 lines
1# Full working Python code
2class Solution:
3    def alphabetBoardPath(self, target: str) -> str:
4        board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
5        pos = {ch: (i, j) for i, row in enumerate(board) for j, ch in enumerate(row)}
6        result = []
7        x, y = 0, 0
8        for char in target:
9            target_x, target_y = pos[char]
10            if target_x < x:
11                result.append('U' * (x - target_x))
12            if target_x > x:
13                result.append('D' * (target_x - x))
14            if target_y < y:
15                result.append('L' * (y - target_y))
16            if target_y > y:
17                result.append('R' * (target_y - y))
18            result.append('!')
19            x, y = target_x, target_y
20        return ''.join(result)

Complexity note: The time complexity is O(n) because we process each character in the target string once, and the space complexity is O(n) due to the storage of character positions in the hashmap.

  • 1Mapping characters to their positions helps in quick access.
  • 2Minimizing moves by calculating differences in coordinates reduces unnecessary steps.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.