A wall is built from rows of bricks. All bricks are one unit tall, but their widths differ, and every row has the same total width. wall[i] lists the widths of the bricks in row i, from left to right.
You draw one straight vertical line from the top of the wall to the bottom. Where the line passes through the seam between two bricks, that row is not crossed. The line may not run along the wall's left or right edge. Return the smallest number of bricks the line can cross.
Example 1
Input: wall = [[1, 2, 1], [3, 1], [2, 2]] Output: 1 Why: rows 0 and 1 both have a seam at width 3
2 more examples and the constraints
Example 2
Input: wall = [[2], [2]] Output: 2 Why: no row has a seam inside, so every row is crossed
Example 3
Input: wall = [[1, 1], [2]] Output: 1 Why: the seam of row 0 at width 1 saves one row
Constraints
- 1 ≤ number of rows ≤ 10,000
- 1 ≤ bricks in a row ≤ 10,000, and at most 20,000 bricks in total
- 1 ≤ wall[i][j] ≤ 2,147,483,647
- Every row has the same total width
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every seam positionO(B·n)
- Count seams in a hash mapO(B)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 rows of two bricks | Verdict |
|---|---|---|---|
| Try every seam position | O(B·n) | Correct; quadratic | |
| Count seams in a hash map | O(B) | Best; one pass over the bricks |
B = total number of bricks, n = number of rows.
Edge cases to test
- One brick per row. [[2], [2]] has no seams at all: the answer is the number of rows.
- Every row shares a seam. [[1, 1], [1, 1]] gives 0.
- A single row. [[3, 4]] gives 0 if it has a seam, 1 if it is one brick.
- Huge widths. Running sums pass 2,147,483,647; a 32-bit sum can wrap and make two different seams look equal.
Common mistakes
- Counting the last brick's end, which is the wall's right edge, so every row seems to share a seam there.
- Keeping the running width in a 32-bit int.
- Trying every x from 1 to the width, when the width can be in the billions.
How to talk through it
- 1Clarify. Is the line allowed on the outer edges? How wide can the wall be?
- 2Give the brute force. Only seam positions matter; test each against every row: O(B·n).
- 3Flip the question. Fewest crossed means most seams. Count seams per position in a map.
- 4Code the one pass. Running sum per row, skip the last brick, track the biggest count.
- 5Test out loud. Run one brick per row, a fully shared seam, and huge widths.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?