Problem Description
Given a brick wall represented as a list of rows with each row containing brick widths, draw a vertical line from the top to the bottom of the wall such that it crosses the least number of bricks. If the line goes through the edge between bricks, that brick is not counted as crossed. The line cannot be drawn along the two vertical edges of the wall. Return the minimum number of crossed bricks after drawing such a vertical line.
Key Insights
- The optimal vertical line should pass through as many brick gaps (edges) as possible.
- For every row, calculate the running sum of brick widths (except for the last brick) to record potential gap positions.
- Use a hash table (or dictionary) to count how many times each gap position occurs across all rows.
- The answer is the number of rows minus the maximum count of gaps that align vertically, since that minimizes the number of bricks crossed.
Space and Time Complexity
Time Complexity: O(N) where N is the total number of bricks (sum of lengths of all rows), since each brick in each row is processed once. Space Complexity: O(M) where M is the number of unique gap positions, which in the worst-case could be proportional to N.
Solution
We iterate through each row and calculate the cumulative sum of brick widths, ignoring the last brick to avoid counting the wall edge. These cumulative sums mark potential vertical gap positions. We use a hash table to keep track of how many rows have a gap at each position. The optimal vertical line goes where the gap count is maximal and thus crosses the minimal number of bricks, which is given by the total number of rows minus this maximum gap count.