Pyramid Transition Matrix — LeetCode 756 Python Solution

MediumBit ManipulationHash TableStringBacktracking
Problem
#756
Reading time
3 min

The problem

You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter.

Example

Input
bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"]
Output
true
Explanation
The allowed triangular patterns are shown on the right.

Python solution

Python
class Solution:
    def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
        @cache
        def dfs(s: str) -> bool:
            if len(s) == 1:
                return True
            t = []
            for a, b in pairwise(s):
                cs = d[a, b]
                if not cs:
                    return False
                t.append(cs)
            return any(dfs("".join(nxt)) for nxt in product(*t))

        d = defaultdict(list)
        for a, b, c in allowed:
            d[a, b].append(c)
        return dfs(bottom)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 756. Pyramid Transition Matrix is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 756. Pyramid Transition Matrix?
LeetCode 756. Pyramid Transition Matrix is rated Medium on LeetCode.
What is the time complexity of LeetCode 756. Pyramid Transition Matrix?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 756. Pyramid Transition Matrix?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 756. Pyramid Transition Matrix cover?
LeetCode 756. Pyramid Transition Matrix is tagged Bit Manipulation, Hash Table, String and Backtracking 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