Taro Logo

Alphabet Board Path

Medium
Google logo
Google
Topics:
Strings

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.

For example:

Input: target = "leet" Output: "DDR!UURRR!!DDD!"

Input: target = "code" Output: "RR!DDRR!UUL!R!"

Constraints:

1 <= target.length <= 100 target consists only of English lowercase letters.

Solution


Brute Force Approach

A brute-force approach would involve exploring all possible paths on the board to construct the target string. This can be done using a graph traversal algorithm such as Depth-First Search (DFS) or Breadth-First Search (BFS).

  1. Start at (0, 0).
  2. Explore all possible moves ('U', 'D', 'L', 'R', '!').
  3. If a path forms the target string, return it.

However, this approach is highly inefficient due to the exponential number of possible paths. It will likely result in a Time Limit Exceeded (TLE) error for larger target strings.

Time Complexity: O(4N), where N is the length of the target string (very high complexity).

Space Complexity: O(N), due to recursion depth or queue size in DFS/BFS.

Optimal Solution

A more efficient solution involves directly calculating the movements required to reach each character in the target string from the current position. We can iterate through the target string and, for each character, determine the sequence of 'U', 'D', 'L', 'R' moves to reach that character from the previous character, appending a '!' to select the character.

Here's a step-by-step breakdown:

  1. Create a mapping of characters to their (row, col) coordinates on the board.
  2. Start at (0, 0).
  3. Iterate through the target string.
  4. For each character:
    • Calculate the row and column differences (dr, dc) between the current position and the target character's position.
    • Generate the movement string using 'U', 'D', 'L', 'R' to adjust the row and column.
    • Append '!' to select the character.
  5. Handle the edge case where we need to move to 'z'. Because moving down and left from any of the first five rows may go out of bounds, we first need to move up to row 4, and move to the left before moving down to the 5th row.
def alphabetBoardPath(target: str) -> str:
    board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
    pos = {}
    for r in range(len(board)):
        for c in range(len(board[r])):
            pos[board[r][c]] = (r, c)

    curr_r, curr_c = 0, 0
    res = ""

    for char in target:
        target_r, target_c = pos[char]
        dr = target_r - curr_r
        dc = target_c - curr_c

        if dr > 0:
            res += "D" * dr
        if dc > 0:
            res += "R" * dc
        if dr < 0:
            res += "U" * abs(dr)
        if dc < 0:
            res += "L" * abs(dc)

        res += "!"
        curr_r, curr_c = target_r, target_c

    return res

Edge Cases

  • Empty target string: Returns an empty string.
  • Target string with non-alphabetic characters (assuming the problem statement guarantees only lowercase letters): no need to handle this based on the prompt.
  • Target string with repeated characters: The algorithm correctly handles cases with repeated characters.
  • Moving to 'z': Special care must be taken to avoid out-of-bounds issues

Time Complexity: O(N), where N is the length of the target string, as we iterate through it once.

Space Complexity: O(1), as we use a constant amount of extra space (ignoring the output string).