You are tasked with building a wall using bricks of various lengths and want to minimize the number of bricks that are crossed by a straight, vertical line. The wall is represented as a list of rows, where each row is a list of integers representing the lengths of bricks in that row, from left to right.
Find the vertical line that crosses the fewest bricks. If there are multiple answers, return any one of them.
Example:
Input:
[[1,2,2,1],
[3,1,2],
[1,3,2],
[2,4],
[3,1,2],
[1,3,1,1]]
Output: 2
With these clarifications in mind, let’s proceed to devise a strategy for the solution.
The key idea here is to find the vertical line that crosses the fewest number of bricks. If the line passes through the edge of bricks between columns, it does not count as crossing through the bricks. We should:
Here’s the Python code that implements the strategy:
def leastBricks(wall):
from collections import defaultdict
# Dictionary to count the edge positions and their occurrences
edge_counts = defaultdict(int)
# Calculate and store edge positions except the wall's total width
for row in wall:
edge_position = 0
for brick in row[:-1]: # exclude the last brick
edge_position += brick
edge_counts[edge_position] += 1
# Find the position that has the maximum edges (minimum bricks crossed)
max_edges = max(edge_counts.values(), default=0)
# Number of rows minus max_edges gives us the minimum bricks to be crossed
return len(wall) - max_edges
# Example usage
wall = [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]]
print(leastBricks(wall)) # Output: 2
The time complexity for this algorithm is O(n * m), where n
is the number of rows in the wall and m
is the average number of bricks per row. This results from iterating over each brick in each row once.
The space complexity is O(w), where w
is the width of the wall since we store edge positions, which is proportional to the width.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?