Number of Ways to Build Sturdy Brick Wall - Problem

You're tasked with building a sturdy brick wall with specific dimensions and constraints. Given a wall of height rows and width units, you must construct it using bricks from an array where each brick has height 1 and width bricks[i].

Key Requirements:

  • Each row must be exactly width units long
  • You have an infinite supply of each brick type
  • Bricks cannot be rotated
  • Sturdy constraint: Adjacent rows cannot have joints at the same position (except at the wall ends)

Return the number of ways to build such a wall, modulo 109 + 7.

Example: With height=2, width=3, bricks=[1,2], you could have row 1 as [2,1] and row 2 as [1,2], since their internal joints don't align.

Input & Output

example_1.py — Basic Case
$ Input: height = 2, width = 3, bricks = [1, 2]
Output: 2
💡 Note: Two valid ways: Row1=[2,1] Row2=[1,2], and Row1=[1,2] Row2=[2,1]. In both cases, internal joints don't align.
example_2.py — Single Row
$ Input: height = 1, width = 4, bricks = [1, 2]
Output: 5
💡 Note: One row can be filled as: [1,1,1,1], [1,1,2], [1,2,1], [2,1,1], [2,2]. All are valid since there's no adjacent row to conflict with.
example_3.py — No Valid Arrangement
$ Input: height = 2, width = 3, bricks = [2]
Output: 0
💡 Note: Width 3 cannot be filled using only bricks of size 2 (3 is odd, but we need even sum). No valid arrangements exist.

Constraints

  • 1 ≤ height ≤ 200
  • 1 ≤ width ≤ 200
  • 1 ≤ bricks.length ≤ 10
  • 1 ≤ bricks[i] ≤ width
  • All bricks[i] are unique
  • Answer fits in 32-bit integer after modulo 109 + 7

Visualization

Tap to expand
Number of Ways to Build Sturdy Brick Wall INPUT Wall: 3 x 2 (width x height) Bricks Array w=1 w=2 Input Parameters height = 2 width = 3 bricks = [1, 2] MOD = 10^9 + 7 ALGORITHM STEPS 1 Find Row Patterns Generate all valid rows [1][2] [2][1] [1][1][1] 2 Build Compatibility Check joint positions Joints: [1,2] vs [2,3] No overlap = Compatible 3 DP Transition dp[row][pattern] count dp[i][j] += dp[i-1][k] if compatible(j, k) 4 Sum All Patterns Sum dp[height-1][*] FINAL RESULT Valid Wall Configuration 1 OK Valid Wall Configuration 2 OK Invalid: Joints Aligned X Output 2 Key Insight: Use DP with two phases: (1) Generate all valid row patterns using backtracking, (2) Build a compatibility graph where edges connect rows without shared joint positions. Then use matrix exponentiation or standard DP to count paths of length 'height' through compatible row patterns. TutorialsPoint - Number of Ways to Build Sturdy Brick Wall | DP Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
38.5K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen