Brick Wall

Draw one vertical line down a wall of bricks so that it crosses as few bricks as possible.

A rectangular wall is built from rows of bricks. The bricks all have the same height but can have different widths, and every row has the same total width. You are given the wall as a list of rows, wall, where each row lists the widths of its bricks from left to right.

Draw one vertical line from the top of the wall to the bottom that crosses as few bricks as possible. A line that runs along the edge between two bricks does not cross either of them. The line may not run along the wall's left or right side. Return the smallest number of bricks the line can cross.

Example 1
Input: wall = [[1, 2, 2, 1], [3, 1, 2], [1, 3, 2], [2, 4], [3, 1, 2], [1, 3, 1, 1]]
Output: 2
Example 2
Input: wall = [[1], [1], [1]]
Output: 3
Explanation: each row is one brick, so any line crosses all three.
Solution

The Idea

Picture a real brick wall and a pencil running straight down it. Cutting through a brick is hard work, so you would rather follow the joints between bricks. The joints do not line up from row to row, so no straight line follows them all the way down. Some lines still follow them more often than others.

Look at the picture below. It draws the six rows of example 1, and the number in each brick is its width. The numbers along the top give the distance from the wall's left side, which we call the position. The wall is 6 wide, so positions run from 0 to 6.

The six rows of example 1 drawn as bricks on positions 0 to 6. A dashed line at position 4 runs along an edge in rows 2, 3, 5 and 6, and crosses one brick in row 1 and one in row 4.

The dashed line is at position 4. In rows 2, 3, 5 and 6, marked "edge", it runs along an edge between two bricks. In rows 1 and 4, marked "crosses", it goes through a brick, so it crosses 2 bricks. That is the answer for example 1.

Why is position 4 the best place? In each row, the line either runs along an edge or crosses exactly one brick. So the bricks crossed are the number of rows minus the rows that have an edge at the line's position. With 6 rows, crossing the fewest bricks means finding the position where the most rows have an edge. Position 4 has an edge in 4 rows, more than any other position, so the line crosses 6 - 4 = 2 bricks.

Where are the edges of a row? Walk along the row and add up the widths. Row 1 is [1, 2, 2, 1]: the first brick ends at 1, the second at 1 + 2 = 3, the third at 5 and the last at 6. A total that grows as you add each new number like this is called a running sum. Every running sum except the last is an edge. The last one, 6, is the wall's right side, where the line may not go.

So the wall never has to be checked position by position. It is enough to collect the running sums of each row and count how many rows share each one. The position with the biggest count is where the line goes.

Solution Approach

Turning that idea into code means settling three things: how to count the edges at each position, how to keep the line off the wall's sides, and what to return when no row has an edge.

Counting edges by position

Why not simply try every position from 1 to the wall's width minus 1? For each position you would check every row, and a wall can be very wide. A row of two bricks, each one billion units wide, is two billion wide but has only one edge. The work should depend on the number of bricks, not on the width.

So the code keeps a HashMap, a Java table from keys to values, from a position to the number of rows with an edge at that position. Each row adds 1 to the count of each of its running sums. For example 1, the counts end as {1: 3, 2: 1, 3: 3, 4: 4, 5: 2}, and the biggest, 4, belongs to position 4. The biggest count can be tracked while counting, so the map never has to be searched afterwards.

Keeping the line off the sides

How do we stop the line from running along a side? The left side is position 0, and a running sum is taken only after a brick has been added, so 0 never shows up. The right side is the last running sum of every row. Stopping one brick before the end of each row leaves it out.

Rows without edges

What if no row has an edge, as in example 2? Each row there is a single brick, so nothing gets counted and the biggest count stays 0. The same rule, rows minus the biggest count, gives 3 - 0 = 3, so this case needs no special code.

Java Solution

The method leastBricks works in these steps:

  1. First, create the map edges, from a position to the number of rows with an edge there, and set mostEdges, the biggest count so far, to 0.
  2. Go through the wall with a loop over its rows. For each row, start a running sum, position, at 0.
  3. Inside, a second loop walks over the bricks of the row and stops before the last one. It adds each brick's width to position, so position is where that brick ends.
  4. Add 1 to the count for position with edges.merge(position, 1, Integer::sum). The call also returns the new count, and mostEdges takes it if it is bigger.
  5. When both loops are done, return wall.size() - mostEdges: the number of rows minus the rows where the line runs along an edge.

The main method runs both examples, a wall where one position is an edge in every row, and a wall of two rows that are each two bricks of one billion units.

Java
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BrickWall {

    public static int leastBricks(List<List<Integer>> wall) {
        Map<Integer, Integer> edges = new HashMap<>(); // position -> rows with an edge there
        int mostEdges = 0;
        for (List<Integer> row : wall) {
            int position = 0;
            for (int i = 0; i < row.size() - 1; i++) { // skip the wall's right side
                position += row.get(i);
                int count = edges.merge(position, 1, Integer::sum);
                mostEdges = Math.max(mostEdges, count);
            }
        }
        return wall.size() - mostEdges;
    }

    public static void main(String[] args) {
        System.out.println(leastBricks(List.of(
                List.of(1, 2, 2, 1), List.of(3, 1, 2), List.of(1, 3, 2),
                List.of(2, 4), List.of(3, 1, 2), List.of(1, 3, 1, 1))));
        System.out.println(leastBricks(List.of(List.of(1), List.of(1), List.of(1))));
        System.out.println(leastBricks(List.of(List.of(2, 3), List.of(2, 1, 2), List.of(1, 1, 3))));
        int big = 1000000000;
        System.out.println(leastBricks(List.of(List.of(big, big), List.of(big, big))));
    }
}

Running it prints:

Output
2
3
0
0

Example 1 gives 2 and example 2 gives 3, as worked out above. Look at the third line, 0. That wall is [[2, 3], [2, 1, 2], [1, 1, 3]], and all three rows have an edge at position 2, so a line there crosses no bricks at all.

The last line is 0 too: both rows have their only edge at one billion. The wall is two billion units wide, yet the method adds just one count per row, because it visits bricks, not positions.

The condition i < row.size() - 1 is what keeps the right side out. With i < row.size() instead, the right side counts as an edge in every row, so mostEdges equals the number of rows. That version printed 0 for all four walls, including 0 instead of 2 and 3 for the two examples.

The original implementation, BrickWall.java, is on GitHub.

Complexity

The work is one step for every brick except the last brick of each row.

  • Time: O(B), where B is the total number of bricks in the wall. Each step is one addition and one map update, which takes O(1) time on average in a HashMap. The width of the wall does not matter.
  • Space: O(B) for the map. In the worst case every edge sits at a different position, so the map gets one entry for each brick that is not last in its row. Besides the map, the method keeps only position and mostEdges.

Running sums, often called prefix sums, also answer range questions quickly in Range Sum Query.