Brick Wall - Problem
Brick Wall Challenge: You're standing in front of a rectangular brick wall with n rows of bricks. Each row contains bricks of the same height (1 unit) but different widths. All rows have the same total width.

Your goal is to draw a vertical line from top to bottom that crosses the minimum number of bricks. Here's the catch: if your line passes through the edge between two bricks, those bricks are not counted as crossed.

Constraints: You cannot draw the line along the leftmost or rightmost edges of the wall.

Input: A 2D array wall where wall[i] contains the widths of bricks in row i
Output: The minimum number of bricks crossed by the optimal vertical line

Input & Output

example_1.py โ€” Basic Wall
$ Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
โ€บ Output: 2
๐Ÿ’ก Note: The optimal vertical line can be drawn at position 4, which only crosses 2 bricks. Most edges align at position 4, so drawing the line there minimizes brick crossings.
example_2.py โ€” Single Row
$ Input: wall = [[1,1,1]]
โ€บ Output: 1
๐Ÿ’ก Note: With only one row of bricks, any vertical line (except at the boundaries) will cross exactly 1 brick. There are only 2 possible positions, and both cross 1 brick.
example_3.py โ€” Aligned Edges
$ Input: wall = [[1,2,3],[1,2,3],[1,2,3]]
โ€บ Output: 0
๐Ÿ’ก Note: All three rows have identical brick patterns, so edges align perfectly at positions 1 and 3. Drawing a line at either position crosses 0 bricks.

Visualization

Tap to expand
Optimal CutEdge at x=240 appears in all 3 rowsResult: 3 rows - 3 aligned edges = 0 bricks crossed
Understanding the Visualization
1
Identify All Edges
Map out where brick boundaries occur in each row
2
Count Alignments
Track how many rows share the same edge positions
3
Choose Optimal Cut
Cut through the edge that appears in the most rows
Key Takeaway
๐ŸŽฏ Key Insight: The minimum crossings occur where the most brick edges align vertically

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n ร— m)

n rows ร— average m bricks per row, visiting each brick once

n
2n
โœ“ Linear Growth
Space Complexity
O(w)

Hash map storing at most w edge positions where w is wall width

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค wall.length โ‰ค 104
  • 1 โ‰ค wall[i].length โ‰ค 104
  • 1 โ‰ค sum(wall[i].length) โ‰ค 2 ร— 104
  • 1 โ‰ค wall[i][j] โ‰ค 104
  • All rows have the same total width
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
89.5K Views
Medium-High Frequency
~18 min Avg. Time
2.8K 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