Problem 1138

Abstract / Summary

Find the path on an alphabet board to spell a target string by moving a cursor and pressing letters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1138.py

class Solution:
    def alphabetBoardPath(self, target: str) -> str:
        # positions of all letters
        board = { }
        for letter in range(26):
            x = letter %  5
            y = letter // 5
            ascii = chr(ord("a") + letter)
            board[ascii] = ( x, y )

        result = ""
        x, y = 0, 0
        for c in target:
            bx = board[c][0]
            by = board[c][1]

            # can't go right if cursor is at "z"
            if y == 5 and x != bx:
                result += "U"
                y -= 1

            # left / right
            while x < bx:
                result += "R"
                x += 1
            while x > bx:
                result += "L"
                x -= 1
            # up / down
            while y < by:
                result += "D"
                y += 1
            while y > by:
                result += "U"
                y -= 1

            # found the letter
            result += "!"

        return result
40 lines | 1043 bytes | submitted November 7, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (100k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation translates a target string into a sequence of moves on a 5-column alphabet board that contains the letters ‘a’ to ‘z’. The board is visualized as a grid where each cell holds a letter; the last row contains only the letter ‘z’. Starting from the top-left corner (position of ‘a’), the algorithm walks to each required letter, appending the directional moves and an exclamation mark to signal selection. The final string of commands is returned.

Construction of the Letter Map

The first phase builds a dictionary that maps every lowercase letter to its (column, row) coordinates. The loop iterates over the 26 letters, computes the column as the remainder of division by 5 and the row as the integer quotient, then stores the pair under the corresponding character key.

board = {}
for letter in range(26):
    x = letter % 5
    y = letter // 5
    ascii = chr(ord("a") + letter)
    board[ascii] = (x, y)

Having this lookup enables constant-time retrieval of any letter’s target coordinates during the navigation stage.

Navigation Loop

The core of the solution iterates through each character of the target string. For each character it extracts the destination column (bx) and row (by) from the pre-computed map.

result = ""
x, y = 0, 0
for c in target:
    bx = board[c][0]
    by = board[c][1]

Special Handling for the ‘z’ Row

Because the board’s last row contains only the cell (0, 5) for ‘z’, moving right from that row would step outside the board. The code checks whether the current row is 5 (the ‘z’ row) and the target column differs from the current column. If so, it first moves up one row, guaranteeing that any subsequent horizontal moves stay within the valid grid.

if y == 5 and x != bx:
    result += "U"
    y -= 1

Horizontal Movement

After the optional upward adjustment, the algorithm aligns the column. It repeatedly appends “R” while the current column is left of the target, and “L” while it is right of the target, updating the cursor position after each step.

while x < bx:
    result += "R"
    x += 1
while x > bx:
    result += "L"
    x -= 1

Vertical Movement

With the column aligned, the code proceeds to adjust the row. It moves down (“D”) while the current row is above the target and moves up (“U”) while it is below, updating the row coordinate accordingly.

while y < by:
    result += "D"
    y += 1
while y > by:
    result += "U"
    y -= 1

Letter Selection

Once the cursor reaches the exact cell of the desired letter, an exclamation mark is appended to indicate that the letter has been “picked”.

result += "!"

The loop repeats this process for every character in the input string, progressively building the complete path.

Edge Cases Addressed

The algorithm explicitly handles the irregular shape of the board caused by the solitary ‘z’ cell. By moving up before any horizontal shift when starting from the ‘z’ row, it avoids illegal rightward moves that would otherwise leave the board’s bounds. This precaution also ensures that when the target is ‘z’ itself, the cursor can approach it from the cell directly above (position (0, 4)) without violating the board layout.

Another implicit edge case is the situation where the target character is the same as the current cursor position. In that scenario, none of the while loops execute, and only the exclamation mark is added, correctly representing a “select current cell” operation.

Performance Optimizations

The solution precomputes the coordinate map for all letters once, eliminating repeated arithmetic during navigation. This dictionary lookup provides O(1) access for each target character. The movement loops use simple while constructs that increment or decrement the cursor coordinates directly, avoiding any unnecessary data structures or function calls. String concatenation is performed incrementally; while Python strings are immutable, the incremental building of a relatively short command sequence (bounded by the length of the target string and the board dimensions) remains efficient for typical input sizes. The overall flow follows a single pass over the target string, ensuring that the algorithm scales linearly with the number of characters to process.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a game board that has all the letters of the alphabet tucked into little squares like a big grid. This code acts like a tiny helper that knows exactly where every letter lives on that grid. It starts at the letter a and gets a list of letters to visit. To get from one letter to the next, the helper looks at the coordinates. It figures out if it needs to move left, right, up, or down to land on the right square. There is a special rule because the letter z is sitting far away from the others in its own corner. If the helper is standing on z, it has to move up before it can go anywhere else. Once the helper lands on the correct square, it shouts out an exclamation mark to show that the letter has been found. The helper continues doing this until every letter in the list has been visited in order.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.65 | σ = 1.30

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
19 links | 11 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

8 solutions   November 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality