⚡Flashcard Drill➔
NeetCode #107LC-554MediumArrays & Hashing
← Back to All Problems

#107 · #554 · Brick Wall(砖墙)

📌 Problem Statement & Constraints

There is a rectangular brick wall made of rows of bricks of varying widths but the same height. Draw a vertical line from the top to the bottom that crosses the fewest bricks. Return that minimum number. The line must not run along an edge at either end of the wall. Constraints: 1 <= wall.length <= 10^4, 1 <= wall[i].length <= 10^4, 1 <= wall[i][j] <= 2^31 - 1.

💡 Core Algorithmic Approaches

  1. A vertical line crosses the fewest bricks where the most brick edges align.
  2. For each row, record the cumulative width after each brick except the last -- the last edge is the right boundary, which is excluded by the problem statement.
  3. Count how many rows have an edge at each cumulative position.
  4. The answer is number_of_rows - max(edge_count). If no interior edge exists anywhere, the line must cross every row, so the answer is the number of rows.

💻 Benchmark Python3 Implementation

class Solution:
    def leastBricks(self, wall: List[List[int]]) -> int:
        from collections import defaultdict
        edges = defaultdict(int)
        for row in wall:
            pos = 0
            for w in row[:-1]:             # exclude the outer right edge
                pos += w
                edges[pos] += 1
        if not edges:
            return len(wall)           # no interior edge -> must cross every row
        return len(wall) - max(edges.values())

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(total bricks): one pass over the wall.
💾 Space Complexity
O(number of distinct edge positions).

⚠️ Interview Pitfalls & Follow-ups

  • Including the final edge of each row: the right boundary of the wall is excluded by the problem, and including it would add every row to the same position, yielding a wrong answer of 0.
  • Using the brick widths instead of cumulative positions: the line position is a cumulative width, not an individual brick width.
  • Returning max(edges.values()): that is the number of rows not crossed; the answer is the complement.
  • Handling a wall with a single brick per row: then there are no interior edges, and the answer is the number of rows.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

砖墙

你的面前有一堵矩形的、由 n 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和相等。你现在要画一条 自顶向下 的、穿过 最少 砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。给你一个二维数组 wall,该数组包含这堵墙的相关信息,返回垂线穿过的 最少 砖块数目。约束:1 ≤ wall.length ≤ 10^4;1 ≤ wall[i].length ≤ 10^4;1 ≤ wall[i][j] ≤ 2^31 − 1;每一行的砖块总宽度相同。

核心要点

  • 找缝隙最密集的位置(核心洞察) :垂线穿过的砖块数 = 行数 − 该位置的缝隙数。因此只需找「被最多行共享的缝隙位置」。
  • 用前缀和定位缝隙 :对每一行累加砖宽,累加值即为该行的内部缝隙位置。注意 最后一块砖的右边界是墙的边缘 ,不算缝隙,因此遍历时要去掉每行的最后一块砖。
  • 哈希计数 :用字典统计每个缝隙位置被多少行共享,答案即 n − max(计数) 。
  • 为什么不能沿墙的边缘画线 :题目明确禁止,因此不需要考虑位置 0 与总宽度处。

常见陷阱

  • 把每行最后一块砖的右边界也计入缝隙 :那是墙的右边缘,题目禁止沿边缘画线。必须遍历 row[:-1] 。这是本题第一大坑。
  • 忘记 default=0 :当墙只有一行且只有一块砖时, gaps 为空, max() 会抛 ValueError。用 default=0 可避免。
  • 对每一行重新计算前缀和 :这是必需的,无法省略;但不要在每块砖处重新求 sum(row[:k]) ,那会退化为 O(n²)。
  • 误以为答案是 max(缝隙数) :答案是「总行数 − 最大缝隙数」,因为穿过砖块数与缝隙数互补。

参考实现

from collections import defaultdict

class Solution:
    def leastBricks(self, wall: list[list[int]]) -> int:
        gaps = defaultdict(int)
        for row in wall:
            pos = 0
            for width in row[:-1]:      # 最后一块砖的右边界是墙边缘,不算缝隙
                pos += width
                gaps[pos] += 1
        # 穿过砖块数 = 总行数 - 最大缝隙共享数
        return len(wall) - max(gaps.values(), default=0)