There is a rectangular brick wall in front of you with
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array
Output: 2
Explanation: If we visualize the

Output: 3
Contents
Solution 1 - At every brick unit, count number of cuts needed from top row to bottom row (Brute force approach) Solution 2 - Find the gaps count at brick position and find the position with maximum gaps, that means less cuts (Efficient approach)
Per the problem statement it is clear that every row will have same width though each brick width may be different.
So, in this approach we are going to get the width of the row as a first step, then
Finally, return the minimum value stored in the
Complexity Analysis:
Time complexity: Above code runs in O(W * H) time where
Space complexity: O(W), since we are storing every brick unit into
In this approach, we will count the gaps at brick position in every row and store this into a
Implementation details:
-
We will first initialize a
HashMap to store the brick position askey and number of gaps found asvalue . -
Then loop through each
row of wall, and store the brick position (i.e. width of current brick) askey and put1 as value if the key doesn't exist, otherwise increment the value.When we loop through each row , we will ignore last brick, because we cannot include edge positions as per problem statement. -
Now, get the maximum number of gaps found, by going through values of
HashMap and get the maximum value. -
Finally subtract the maximum number of gaps found from
wall height , this will give minimum number of cuts needed to reach from top row to bottom row.
Let's look at an example, say if the given input wall is
-
After going through first row
[1, 2, 2, 1] , gaps map will look like this.Gaps Position Gaps 1 1 3 1 5 1 -
After going through second row
[3, 1, 2] , gaps map will look like this.Gaps Position Gaps 1 1 3 2 4 1 5 1 -
After going through third row
[1, 3, 2] , gaps map will look like this.Gaps Position Gaps 1 2 3 2 4 2 5 1 -
After going through fourth row
[2, 4] , gaps map will look like this.Gaps Position Gaps 1 2 2 1 3 2 4 2 5 1 -
After going through fifth row
[3, 1, 2] , gaps map will look like this.Gaps Position Gaps 1 2 2 1 3 3 4 3 5 1 -
After going through sixth row
[1, 3, 1, 1] , gaps map will look like this.Gaps Position Gaps 1 3 2 1 3 3 4 4 5 2 -
As we can see the maximum number of gaps found are
4 , we will subtract this from wall height which is6 -4 = 2 . So we need to cut a minimum of2 bricks to reach from top row to bottom row.
Complexity Analysis:
Time complexity: Above code runs in O(m *n) time where
Space complexity: O(m) since we are storing position index to gap count into a
Above implementations source code can be found at