Problem 756

Abstract / Summary

Determine if a pyramid can be built by moving blocks between layers using a given transition matrix.

Note

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

Python 0756.py

class Solution:
    def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
        # store top element of each triangle
        up = defaultdict(str)
        for a in allowed:
            up[a[ : 2]] += a[2]

        @cache
        def deeper(row, next = ""):
            if len(row) == 1:
                # final triangle
                if not next:
                    return True
                # begin new row
                return deeper(next, "")

            return any(deeper(row[1 :], next + u) for u in up[row[: 2]])

        return deeper(bottom)
19 lines | 595 bytes | submitted May 19, 2024 | GitHub   23% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Backtracking
  • Bit Manipulation
  • 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 provided implementation solves the classic “Pyramid Transition” problem. Given a bottom row of characters and a list of allowed three-character strings, the algorithm determines whether it is possible to build a pyramid by repeatedly placing a character on top of each adjacent pair, respecting the allowed triples. The solution follows a depth-first search strategy with memoization to avoid redundant work.

Construction of the Transition Map

The first logical block creates a dictionary that maps every possible pair of adjacent characters to the set of characters that may appear above them.

up = defaultdict(str)
for a in allowed:
    up[a[:2]] += a[2]

By iterating over the allowed list, each triple a contributes its third character to the string stored under the key formed by its first two characters. This compact representation enables constant-time lookup of all viable upper characters for any pair.

Recursive Exploration with Memoization

The core of the algorithm is the nested function deeper, which is decorated with @cache. This decorator automatically stores the result of each call keyed by its arguments, ensuring that identical sub-problems are solved only once.

@cache
def deeper(row, next=""):
    if len(row) == 1:
        if not next:
            return True
        return deeper(next, "")
    return any(deeper(row[1:], next + u) for u in up[row[:2]])

Base Condition

When the current row contains a single character, the algorithm has reached the apex of the current sub-pyramid. If the next string is empty, it means the whole pyramid has been successfully constructed, and the function returns True. Otherwise, the next string represents the next row to be processed, and the recursion restarts with that row.

Recursive Step

For rows longer than one character, the function examines the first two characters (row[:2]). It retrieves all possible upper characters from up. For each candidate u, it appends u to the growing next string and recursively calls deeper on the remainder of the row (row[1:]). The use of any ensures that the search stops as soon as a successful construction path is found.

Edge Cases Handled

The algorithm gracefully handles several edge conditions without explicit checks.

When the allowed list is empty, the up dictionary contains no entries. Consequently, the generator expression inside any yields no candidates, and any returns False, correctly indicating that no pyramid can be built.

If the bottom string consists of a single character, the initial call to deeper receives a row of length one. The base condition detects this immediately, and because next is empty, the function returns True, reflecting that a pyramid of height zero is trivially possible.

When multiple allowed triples share the same lower pair, the concatenation in up aggregates all possible upper characters. The recursive step iterates over each of them, ensuring that every viable path is explored.

The memoization cache automatically collapses duplicate sub-problems that arise from different traversal orders, preventing exponential blow-up in cases where many rows share common suffixes.

Performance Optimizations

Two primary techniques contribute to the efficiency of the solution.

First, the use of a defaultdict(str) to store possible upper characters as a concatenated string enables fast retrieval and iteration without the overhead of constructing intermediate collections.

Second, the @cache decorator provides automatic memoization. By caching the result of each (row, next) pair, the algorithm avoids recomputing the same sub-pyramid configurations, which dramatically reduces the number of recursive calls in dense search spaces.

The early-exit behavior of any further trims the search tree. As soon as a successful path is discovered for a given row, the function returns True without exploring remaining candidates, saving unnecessary work.

Invocation

The public method simply forwards the bottom row to the recursive engine.

return deeper(bottom)

Because deeper is fully self-contained, the outer method remains concise, delegating all logical responsibilities to the cached helper.

Overall, the code presents a clear, compact solution that leverages Python’s built-in features-defaultdict, function caching, and generator expressions-to achieve an elegant depth-first search with effective pruning.

written by openai gpt

ELI5 - Simplified Explanation

Imagine building a tower out of blocks. At the base, there is a long row of colored blocks. To build the next level up, you need to place a block on top of every pair of blocks below it. The rules say that two specific blocks sitting side by side are only allowed to have one certain color of block on top of them.

This code works like a persistent builder trying to finish the tower. First, it makes a special list that remembers which blocks can fit on top of every possible pair. Once it knows the rules, it looks at the bottom row. It picks a pair, checks the rules to see what color could go on top, and places it there. Then it moves to the next pair in that same row.

After it finishes a full row, it looks at the new row it just created and starts building the next level on top of that. It keeps going row by row until the tower reaches a single block at the very peak. If it finds a way to place blocks so that every level fits together perfectly until reaching the top, it knows the tower can be finished. It is just like exploring different ways to stack blocks to see which paths lead all the way to the top.

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 | μ = 7.15 | σ = 1.35

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Python Java
leetcode.ca C++ Rust Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
halfrost Go
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
withaarzoo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
withaarzoo C++
zfang399 C++
29 links | 15 authors | 8 languages

Videos

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

Solved On The Same Day

1 medium
2 solutions   May 19, 2024

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