Brick Wall - Problem

There is a rectangular brick wall in front of you with n rows of bricks. The i-th row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.

Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.

Input & Output

Example 1 — Standard Wall
$ Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,1,1],[1,1,2,2]]
Output: 2
💡 Note: The wall has 6 rows. Drawing a vertical line at position 4 passes through edges of 4 rows, so it crosses only 2 bricks (6-4=2).
Example 2 — Single Column
$ Input: wall = [[1],[1],[1]]
Output: 3
💡 Note: All rows have only one brick each, so any vertical line must cross all 3 bricks. No edges exist except at boundaries.
Example 3 — Perfect Alignment
$ Input: wall = [[2,1],[2,1],[2,1]]
Output: 0
💡 Note: All rows have an edge at position 2, so we can draw a line there that crosses 0 bricks.

Constraints

  • n == wall.length
  • 1 ≤ n ≤ 104
  • 1 ≤ wall[i].length ≤ 104
  • 1 ≤ sum(wall[i].length) ≤ 2 × 104
  • 1 ≤ wall[i][j] ≤ 231 - 1
  • For each row i, sum(wall[i]) is the same.

Visualization

Tap to expand
Brick Wall: Find Minimum Crossed Bricks122131213224Optimal Cut PositionEdge at position 4 appears in 4 out of 4 visible rowsResult: Minimum 2 bricks crossed
Understanding the Visualization
1
Input Wall
2D array representing brick widths in each row
2
Find Edges
Calculate where bricks end in each row
3
Optimal Cut
Cut at position with most aligned edges
Key Takeaway
🎯 Key Insight: The best cut line passes through the most brick edge positions (seams between bricks)
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 18
87.0K Views
Medium Frequency
~15 min Avg. Time
2.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