Before attempting this problem, you should be comfortable with:
The goal is to draw a vertical line through the wall that crosses the fewest bricks. A line crosses a brick only if it doesn't pass through a gap between bricks. So we need to find the vertical position where the most gaps align across all rows.
The brute force approach is straightforward: for every possible vertical position (from 1 to wall width minus 1), count how many rows do NOT have a gap at that position. The position with the fewest cuts is our answer.
1 to width - 1:class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
n = len(wall)
m = 0
for brick in wall[0]:
m += brick
gaps = [[] for _ in range(n)]
for i in range(n):
gap = 0
for brick in wall[i]:
gap += brick
gaps[i].append(gap)
res = n
for line in range(1, m):
cuts = 0
for i in range(n):
if line not in gaps[i]:
cuts += 1
res = min(res, cuts)
return resWhere is the sum of widths of the bricks in the first row, is the number of rows and is the average number of gaps in each row.
Instead of checking every possible vertical position, we can think about this differently. We want to maximize the number of gaps we pass through, because each gap means we avoid cutting a brick. If we count how many times each gap position appears across all rows, the position with the most gaps is the best place to draw our line. The answer is then total rows minus the maximum gap count.
Where is the total number of bricks in the wall and is the total number of gaps in all the rows.
The rightmost edge of the wall (at position equal to total width) should not be counted as a gap since a line there wouldn't cross any bricks anyway. Including it inflates the gap count and gives wrong answers.
# Wrong: counting all gaps including the last one
for brick in row:
total += brick
countGap[total] += 1 # Counts wall edge
# Correct: exclude the last brick
for i in range(len(row) - 1):
total += row[i]
countGap[total] += 1The answer is number_of_rows - max_gaps, not just max_gaps. Maximizing gaps minimizes cuts, but forgetting to subtract from total rows returns the wrong value.
If a row contains only one brick spanning the entire width, it has no internal gaps. The hash map initialization with {0: 0} handles the edge case where no gaps exist, ensuring the answer defaults to cutting through all rows.