Alphabet Board Path — LeetCode 1138 Python Solution

MediumHash TableString
Problem
#1138
Pattern
Hash Map
Reading time
4 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def alphabetBoardPath(self, target: str) -> str:
        i = j = 0
        ans = []
        for c in target:
            v = ord(c) - ord("a")
            x, y = v // 5, v % 5
            while j > y:
                j -= 1
                ans.append("L")
            while i > x:
                i -= 1
                ans.append("U")
            while j < y:
                j += 1
                ans.append("R")
            while i < x:
                i += 1
                ans.append("D")
            ans.append("!")
        return "".join(ans)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string target, as each character in the string target needs to be traversed
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1138. Alphabet Board Path is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1138. Alphabet Board Path?
LeetCode 1138. Alphabet Board Path is rated Medium on LeetCode.
What is the time complexity of LeetCode 1138. Alphabet Board Path?
The Python solution on this page runs in O(n), where n is the length of the string target, as each character in the string target needs to be traversed.
What is the space complexity of LeetCode 1138. Alphabet Board Path?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1138. Alphabet Board Path cover?
LeetCode 1138. Alphabet Board Path is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview