Brick Wall (LeetCode 554): Solution and Explanation

Medium
Array
Hash Table

Draw one vertical line through a wall of brick rows so it cuts as few bricks as possible. A line that runs along a seam between two bricks does not cut either one.

Intuition

Look at one row. A vertical line at position x avoids cutting that row only if the row has a seam exactly at x. Otherwise it passes through some brick.

So for any position, bricks cut = number of rows minus number of rows with a seam there. Minimizing cuts means finding the position where the most rows have a seam.

Seam positions inside a row are its prefix sums. Count each prefix sum across all rows in a hash map, leaving out the last brick because its right end is the wall's outer edge.

Approach: Hash map of seam positions

  1. Create an empty map edges from position to count, and set best = 0.
  2. For each row, walk its bricks except the last one with a running sum pos.
  3. After each brick, increment edges[pos] and update best with the new count.
  4. Return len(wall) - best.

Step-by-step example

wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
  1. Row 0 has seams at 1, 3 and 5. Row 1 has seams at 3 and 4.
  2. Row 2 adds seams at 1 and 4. Row 3 adds a seam at 2.
  3. Row 4 adds 3 and 4. Row 5 adds 1, 4 and 5.
  4. Position 4 now has a count of 4, the largest. A line there cuts the other 6 - 4 = 2 rows, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def leastBricks(self, wall: List[List[int]]) -> int:
3        edges = {}
4        best = 0
5        for row in wall:
6            pos = 0
7            for width in row[:-1]:
8                pos += width
9                edges[pos] = edges.get(pos, 0) + 1
10                best = max(best, edges[pos])
11        return len(wall) - best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(N)

N is the total number of bricks. Each brick adds one prefix sum and one hash map update.

Space

O(M)

M is the number of distinct seam positions stored in the map, at most N.

Other approaches

Try every position (time O(width * n), space O(1))

Sweep every integer position from 1 to the wall width and count crossings. The width can be up to 2^31 - 1, so this is far too slow.

Sort all seam positions (time O(N log N), space O(N))

Collect every prefix sum into one list, sort it, and find the longest run of equal values. Correct, but the sort adds a log factor the hash map avoids.

Common mistakes

  • Counting the last brick's right end. That position is the wall's outer edge, every row has it, and the line is not allowed there.
  • Calling max on an empty map. When every row is a single brick there are no seams, and the answer is the number of rows.
  • Iterating over positions instead of bricks. Brick widths can be huge, so only the seam positions that actually occur should be visited.
  • Returning the largest count itself instead of rows minus that count.

Frequently asked questions

Why does the answer use the number of rows?

Every row contributes exactly one cut brick unless it has a seam at the line's position. So cuts = rows minus rows with a seam there.

Can the prefix sums overflow a 32-bit integer?

No. Every row sums to at most 2^31 - 1, and the last brick is skipped, so each seam position stays below that limit.

Does it matter which position wins a tie?

No. Only the count is returned, so any position with the largest count gives the same answer.