Brick Wall
Master this topic with zero to advance depth.
Brick Wall
There is a rectangular brick wall in front of you. The wall is n rows high and the width is the same for each row. You want to draw a vertical line from the top to the bottom and cross the least number of bricks. Each row is represented by a list of brick widths. A line crosses a brick if it passes through its interior, but not its edge.
Visual Representation
Row 1: [1, 2, 2, 1] -> Edges at: 1, 3, 5
Row 2: [3, 1, 2] -> Edges at: 3, 4
Frequency of Edges:
1: 1
3: 2 (Max! Draw line here)
5: 1
4: 1
Min bricks crossed = Total Rows - Max Edge FrequencyExamples
Level I: Brute Force
Intuition
Check every possible vertical line position (at every 0.5 unit width up to total width). For each position, count how many bricks are crossed. Extremely slow.
Detailed Dry Run
Width=6. Check 1, 2, 3, 4, 5. Line at 3: Row1 (edge), Row2 (edge)... Crosses 0 bricks in those rows.
Level II: HashMap (Edge Frequency)
Intuition
A line crosses the least bricks if it passes through the most edges. We use a HashMap to count the frequency of edges (prefix sums) at each position (excluding the far right edge).
Detailed Dry Run
Row: [1, 2, 2, 1] -> Edges: {1:1, 3:1, 5:1} Row: [3, 1, 2] -> Edges: {1:1, 3:2, 5:1, 4:1} Max edges = 2 (at pos 3). Min bricks = Rows(2) - Max(2) = 0.
Level III: Optimal Solution (Pointer-based Merge)
Intuition
Similar to merging K sorted lists, we can treat each row's edges as a sorted list. Use pointers to advance through edges across all rows, counting occurrences at each position. This is more efficient if the number of bricks is massive but rows are few.
Detailed Dry Run
Row 1: [1, 2, 2, 1] -> Edges: [1, 3, 5] Row 2: [3, 1, 2] -> Edges: [3, 4] Initially: ptrs=[0, 0]. Curr Edges: [1, 3]. Min is 1. Pop 1. Next min is 3. Pop 3 from both. Count=2.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.