Brick Wall - Problem
Brick Wall Challenge: You're standing in front of a rectangular brick wall with
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
Output: The minimum number of bricks crossed by the optimal vertical line
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 iOutput: 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
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
โ Linear Growth
Space Complexity
O(w)
Hash map storing at most w edge positions where w is wall width
โ 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code