KatInterview

757. Pyramid Transition Matrix

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks whether we can construct a pyramid from a given bottom row up to a single-block top. The construction must follow a given set of allowed triangular patterns. A pattern "ABC" means a block 'C' can be placed on top of an 'A' (left) and 'B' (right) pair.

Solution

Pyramid Transition Matrix in Python

from collections import defaultdict

class Solution:
    def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
        # Preprocess 'allowed' into a more efficient map for lookups.
        # Key: 2-char string for the base, Value: list of possible top chars.
        self.transitions = defaultdict(list)
        for s in allowed:
            self.transitions[s[:2]].append(s[2])
        
        # Set for memoization to store states (rows) that cannot form a pyramid.
        self.memo = set()
        
        return self._solve(bottom)

    def _solve(self, current_row: str) -> bool:
        # Base case: If the row has only one block, we've reached the top.
        if len(current_row) == 1:
            return True
        # Memoization: If we've already determined this row is a dead end, return False.
        if current_row in self.memo:
            return False

        # Try to build the next level. If any valid next level can lead to a solution,
        # then 'current_row' is a valid state.
        # This is done by generating all possible next rows and checking them.
        for next_row in self._generate_next_rows(current_row):
            if self._solve(next_row):
                return True

        # If no possible next level leads to a solution, mark this row as a dead end.
        self.memo.add(current_row)
        return False

    def _generate_next_rows(self, current_row: str):
        # A generator function to yield all possible next rows using backtracking.
        def backtrack(next_row_so_far, index):
            # Base case: A full 'next_row' has been constructed.
            if index == len(current_row) - 1:
                yield next_row_so_far
                return
            
            # Get the pair of blocks from the 'current_row'.
            base = current_row[index:index+2]
            if base in self.transitions:
                # Iterate through all possible top blocks for the current 'base' pair.
                for char in self.transitions[base]:
                    # Recursively build the rest of the 'next_row'.
                    yield from backtrack(next_row_so_far + char, index + 1)

        yield from backtrack("", 0)

Pyramid Transition Matrix in Java

class Solution {
    // Map to store allowed transitions for efficient lookup.
    private Map<String, List<Character>> transitions = new HashMap<>();
    // Set for memoization to store states (rows) that cannot form a pyramid.
    private Set<String> memo = new HashSet<>();

    public boolean pyramidTransition(String bottom, List<String> allowed) {
        // Preprocess 'allowed' into the transitions map.
        // Key: 2-char string for the base, Value: list of possible top chars.
        for (String s : allowed) {
            String base = s.substring(0, 2);
            transitions.putIfAbsent(base, new ArrayList<>());
            transitions.get(base).add(s.charAt(2));
        }
        return solve(bottom);
    }

    // Main recursive function to check if a pyramid can be built from 'currentRow'.
    private boolean solve(String currentRow) {
        // Base case: If the row has only one block, we've reached the top.
        if (currentRow.length() == 1) {
            return true;
        }
        // Memoization: If we've already determined this row is a dead end, return false.
        if (memo.contains(currentRow)) {
            return false;
        }

        // Try to build the next level. If any valid next level can lead to a solution,
        // then 'currentRow' is a valid state.
        if (buildNextLevel(currentRow, "", 0)) {
            return true;
        }

        // If no possible next level leads to a solution, mark this row as a dead end.
        memo.add(currentRow);
        return false;
    }

    // Helper function to build the next level using backtracking.
    // It explores all possible valid next rows.
    private boolean buildNextLevel(String currentRow, String nextRow, int index) {
        // Base case: A full 'nextRow' has been constructed.
        // Now, we check if a pyramid can be built starting from this 'nextRow'.
        if (index == currentRow.length() - 1) {
            return solve(nextRow);
        }

        // Get the pair of blocks from the 'currentRow' to place a block on top of.
        String base = currentRow.substring(index, index + 2);
        
        // If there are no allowed transitions for this base pair, this path is invalid.
        if (!transitions.containsKey(base)) {
            return false;
        }

        // Iterate through all possible top blocks for the current 'base' pair.
        for (char c : transitions.get(base)) {
            // Recursively try to build the rest of the 'nextRow'.
            // If it returns true, it means a valid pyramid was found.
            if (buildNextLevel(currentRow, nextRow + c, index + 1)) {
                return true;
            }
        }

        // If we've tried all possibilities for this position and none worked, backtrack.
        return false;
    }
}

Pyramid Transition Matrix in C++

class Solution {
public:
    bool pyramidTransition(string bottom, vector<string>& allowed) {
        // Preprocess 'allowed' into a more efficient map for lookups.
        // Key: 2-char string for the base, Value: vector of possible top chars.
        for (const string& s : allowed) {
            transitions[s.substr(0, 2)].push_back(s[2]);
        }
        return solve(bottom);
    }

private:
    // Map to store allowed transitions.
    unordered_map<string, vector<char>> transitions;
    // Set for memoization to store states (rows) that cannot form a pyramid.
    unordered_set<string> memo;

    // Main recursive function to check if a pyramid can be built from 'currentRow'.
    bool solve(const string& currentRow) {
        // Base case: If the row has only one block, we've reached the top.
        if (currentRow.length() == 1) {
            return true;
        }
        // Memoization: If we've already determined this row is a dead end, return false.
        if (memo.count(currentRow)) {
            return false;
        }

        // Try to build the next level. If any valid next level can lead to a solution,
        // then 'currentRow' is a valid state.
        if (buildNextLevel(currentRow, "", 0)) {
            return true;
        }

        // If no possible next level leads to a solution, mark this row as a dead end.
        memo.insert(currentRow);
        return false;
    }

    // Helper function to build the next level using backtracking.
    // It explores all possible valid next rows.
    bool buildNextLevel(const string& currentRow, string nextRow, int index) {
        // Base case: A full 'nextRow' has been constructed.
        // Now, we check if a pyramid can be built starting from this 'nextRow'.
        if (index == currentRow.length() - 1) {
            return solve(nextRow);
        }

        // Get the pair of blocks from the 'currentRow' to place a block on top of.
        string base = currentRow.substr(index, 2);
        
        // If there are no allowed transitions for this base pair, this path is invalid.
        if (transitions.find(base) == transitions.end()) {
            return false;
        }

        // Iterate through all possible top blocks for the current 'base' pair.
        for (char c : transitions[base]) {
            // Recursively try to build the rest of the 'nextRow'.
            // If it returns true, it means a valid pyramid was found.
            if (buildNextLevel(currentRow, nextRow + c, index + 1)) {
                return true;
            }
        }

        // If we've tried all possibilities for this position and none worked, backtrack.
        return false;
    }
};

Pyramid Transition Matrix in TypeScript

function pyramidTransition(bottom: string, allowed: string[]): boolean {
    // Preprocess 'allowed' into a more efficient map for lookups.
    const transitions = new Map<string, string[]>();
    for (const s of allowed) {
        const base = s.substring(0, 2);
        if (!transitions.has(base)) {
            transitions.set(base, []);
        }
        transitions.get(base)!.push(s[2]);
    }

    // Set for memoization to store states (rows) that cannot form a pyramid.
    const memo = new Set<string>();

    // Main recursive function to check if a pyramid can be built from 'currentRow'.
    function solve(currentRow: string): boolean {
        // Base case: If the row has only one block, we've reached the top.
        if (currentRow.length === 1) {
            return true;
        }
        // Memoization: If we've already determined this row is a dead end, return false.
        if (memo.has(currentRow)) {
            return false;
        }

        // Try to build the next level. If any valid next level can lead to a solution,
        // then 'currentRow' is a valid state.
        if (buildNextLevel(currentRow, "", 0)) {
            return true;
        }

        // If no possible next level leads to a solution, mark this row as a dead end.
        memo.add(currentRow);
        return false;
    }

    // Helper function to build the next level using backtracking.
    // It explores all possible valid next rows.
    function buildNextLevel(currentRow: string, nextRow: string, index: number): boolean {
        // Base case: A full 'nextRow' has been constructed.
        // Now, we check if a pyramid can be built starting from this 'nextRow'.
        if (index === currentRow.length - 1) {
            return solve(nextRow);
        }

        // Get the pair of blocks from the 'currentRow' to place a block on top of.
        const base = currentRow.substring(index, index + 2);

        // If there are no allowed transitions for this base pair, this path is invalid.
        if (!transitions.has(base)) {
            return false;
        }

        // Iterate through all possible top blocks for the current 'base' pair.
        for (const char of transitions.get(base)!) {
            // Recursively try to build the rest of the 'nextRow'.
            // If it returns true, it means a valid pyramid was found.
            if (buildNextLevel(currentRow, nextRow + char, index + 1)) {
                return true;
            }
        }

        // If we've tried all possibilities for this position and none worked, backtrack.
        return false;
    }

    return solve(bottom);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.