Crossing the least number of bricks is equivalent to crossing the most number of edges. We use a hash map to count the frequencies of the vertical edges (positions) across all rows.
- Initialize
edges = {0: 0}. - For each
rowinwall:curr_pos = 0.- Iterate through bricks in
row(except the last one):curr_pos += brick_width.edges[curr_pos] = edges.get(curr_pos, 0) + 1.
- The number of rows is
len(wall). - Max edges found is
max(edges.values()). - Minimum crossed bricks =
total_rows - max_edges.
- Time Complexity: O(N), where N is total bricks.
- Space Complexity: O(W), where W is the width of the wall (or number of unique edge positions).
def least_bricks(wall):
edges = {0: 0} # map position to edge count
for row in wall:
pos = 0
for brick in row[:-1]:
pos += brick
edges[pos] = edges.get(pos, 0) + 1
return len(wall) - max(edges.values())