Problem Description
You need to build a wall with a given height and width using bricks of fixed height (1) but varying widths (given in the bricks array). Each row of the wall must exactly fill the width. Furthermore, to ensure the wall is sturdy, no two adjacent rows can have brick joints (the boundaries where one brick ends and the next begins) line up at the same position except at the two ends. Return the number of ways to build such a sturdy wall modulo 10^9 + 7.
Key Insights
- First, generate all valid ways (configurations) to fill a row. Each configuration can be represented as a bitmask where bits represent positions (from 1 to width-1) of brick joints.
- Use recursion/backtracking to construct rows by placing bricks sequentially and recording the join positions (except at position 0 and width).
- Two rows (bitmask configurations) are compatible if they do not have a joint at the same position; in other words, the bitwise AND of the two bitmasks is zero.
- Use dynamic programming over the height of the wall where each state represents the current row configuration.
- Precompute a compatibility graph (or list) to quickly iterate over valid transitions from one row configuration to the next.
Space and Time Complexity
Time Complexity: O(height * R^2) where R is the number of valid row configurations (R is small since width ≤ 10).
Space Complexity: O(height * R) for the dynamic programming table along with O(R^2) for compatibility storage.
Solution
We begin by generating all valid row configurations by recursively placing bricks from a given position until we reach the wall’s width. Each time we place a brick, if we have not reached the end of the row, we mark the join position in a bitmask. Next, we build a compatibility list to record which pairs of configurations can be stacked (their bitmasks must have no common 1 bits). Finally, we use a DP approach where dp[row][config] represents the number of ways to construct the wall up to that row with the ending row using configuration config. The initial row is filled with any valid configuration, and we then “stack” rows by adding only those configurations that are compatible with the previous one. Sum up all possibilities for the final row and take modulo 10^9 + 7.