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 Problem - Hash Map Approach INPUT 1 2 3 4 5 6 Input Array: [1,2,2,1] [3,1,2] [1,3,2] [2,4] [3,1,1,1] [1,1,2,2] 6 rows, width = 6 ALGORITHM STEPS 1 Count Edge Positions Track cumulative widths for each row (exclude end) 2 Build Hash Map Key: edge position Value: count of edges Edge Count Map pos 1: 3 edges pos 2: 3 edges pos 3: 4 edges pos 4: 4 edges (MAX) pos 5: 2 edges MAX 3 Find Max Edges Max edges at pos = 4 4 Calculate Result rows - maxEdges = 6-4 = 2 Min crossed = Total rows - Max edges FINAL RESULT pos=4 X X Legend: Vertical line X = Crossed brick OUTPUT 2 Min bricks crossed = 2 (at position 4) Key Insight: Instead of counting bricks crossed, count edges at each position using a hash map. The optimal line passes through the position with MAXIMUM edges (minimum crossings). Formula: min_crossed = total_rows - max_edges_at_any_position | Time: O(n), Space: O(width) TutorialsPoint - Brick Wall | Hash Map Approach
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