There is a rectangular brick wall with rows of bricks. The bricks in each row have various integer widths. You want to draw a vertical line from the top to the bottom that cuts through the fewest number of bricks. The line must go through the wall between two adjacent bricks at the same horizontal position across every row. Bricks on the edges (at position 0 and at the total width) do not count as cuts.
A brute force approach would check every possible horizontal position between bricks in the first row. But a hash map makes this efficient: count how many rows have a brick edge at each position. For each row, compute prefix sums of brick widths — these are the edge positions where a blank row has its gaps. Increment a counter in the hash map for each edge position (excluding the total width, which is the wall's right edge).
The vertical line that cuts through the fewest bricks is the position with the most edge alignments. Since each row has exactly one gap at each edge position, if N rows have an edge at position x, then a line at x cuts through (wall height - N) bricks. The answer is simply the height of the wall minus the maximum count from the hash map.
Edge cases include a wall with a single row of one brick (the line must cut that brick since there are no gaps), and a wall where all rows have the same brick arrangement (the optimal line goes through the shared gap).
Example Input & Output
No edges except ends, so cut must go through all 3 bricks.
Position 1 has edges in all rows, so cut = 3-3 = 0.
Most edges at position 3 (rows 2,3,5), so cut = 6-4 = 2 bricks.
Position 1 has edges in all rows.
No shared edge position. Best is 1 row aligned, so cut = 2-1 = 1.
Algorithm Flow

Solution Approach
Compute prefix sums for each row. Store edge position frequencies in a hash map. The answer is height - max frequency (or height if no edge aligns).
Time O(N * M) where N=rows, M=bricks per row. Space O(total edge positions).
Best Answers
import java.util.*;
class Solution {
public int solution(int[][] wall) {
Map<Integer,Integer> freq = new HashMap<>();
int best = 0;
for (int[] row : wall) {
int sum = 0;
for (int i = 0; i < row.length - 1; i++) {
sum += row[i];
int val = freq.getOrDefault(sum, 0) + 1;
freq.put(sum, val);
if (val > best) best = val;
}
}
return wall.length - best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
