Problem 554

Abstract / Summary

Find the least number of bricks crossed when breaking a wall into vertical lines to go straight through it.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0554.py

class Solution:
    def leastBricks(self, wall: List[List[int]]) -> int:
        gaps = defaultdict(int)
        gaps[0] = 0 # ignore left border

        for row in wall:
            pos = 0
            for r in row[:-1]: # ignore right border
                pos += r
                gaps[pos] += 1

        return len(wall) - max(gaps.values())
12 lines | 360 bytes | submitted October 5, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “brick wall” problem: given a wall represented as a list of rows, each row containing brick widths, it determines the minimum number of bricks that a vertical line must cross. The algorithm builds a frequency map of all interior edge positions (gaps) across rows, then selects the position that aligns with the most gaps. The answer is the total number of rows minus that maximum frequency, which corresponds to the fewest bricks intersected.

Key Steps

The solution can be broken down into distinct logical sections, each reflected in a concise code fragment.

Initialize the gap counter A dictionary with default integer values is created to store how many rows contain a gap at a particular cumulative position. The left border (position 0) is explicitly set to zero because a line drawn at the extreme left is not considered a valid crossing point.

gaps = defaultdict(int)
gaps[0] = 0  # ignore left border

Iterate over each row and accumulate positions For every row, a running sum pos tracks the distance from the left edge. The inner loop processes all bricks except the last one in the row, because the rightmost edge of the wall is also not a valid crossing point. Each intermediate cumulative position is recorded in the gaps map.

for row in wall:
    pos = 0
    for r in row[:-1]:  # ignore right border
        pos += r
        gaps[pos] += 1

Compute the result After all rows have been examined, the dictionary holds the count of rows that share each interior gap. The most common gap yields the maximal number of rows that a line can pass through without cutting a brick. Subtracting this count from the total number of rows gives the minimal number of bricks intersected.

return len(wall) - max(gaps.values())

Edge Cases Handled

The algorithm deliberately skips the first and last brick of each row. This design automatically handles walls where a row consists of a single brick: the inner loop receives an empty slice, leaving pos unchanged and ensuring no gap is recorded for that row. Consequently, the gaps dictionary may contain only the initial entry 0:0 when no interior gaps exist, and max(gaps.values()) correctly evaluates to 0. The final subtraction then yields the total number of rows, which is the correct answer when every possible line must cut through at least one brick.

Another subtle edge case is when multiple rows share the same cumulative position. The use of a defaultdict(int) guarantees that each occurrence increments the existing count, correctly aggregating the frequency of that gap across all rows.

Performance Optimizations

The implementation leverages a hash map (defaultdict) to achieve constant-time updates for each gap position, avoiding the need for secondary data structures or sorting. By processing each brick exactly once and updating the map in place, the algorithm runs in a single pass over the input data. The exclusion of the last brick in each row prevents unnecessary entries for the rightmost wall boundary, reducing the size of the map and the work required for the final max operation. The final computation uses len(wall) directly, which is an O(1) operation, and max(gaps.values()) scans only the distinct gap positions rather than every brick, further minimizing overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you are building a big wall out of colorful toy bricks. Each row of the wall has bricks of different sizes placed side by side. When you look at the whole wall, you want to draw a straight line from the top to the bottom, but you want that line to go through as few bricks as possible.

To solve this, first start with a notebook to keep track of all the places where two bricks meet. Every time a brick ends, that is a spot where a gap exists. Look at each row one by one and walk across it. Whenever a brick ends, mark that spot in the notebook by adding one to the count for that position. Once the entire wall is checked, look through the notebook to see which position has the most gaps. If many rows have a gap at the exact same spot, it means a perfect line can go through all of them. The final step is to take the total number of rows and subtract the number of gaps found at that most popular spot. This tells how many bricks would be broken if you drew a line through the best gap.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.50

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
fpdjsns Python
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
fpdjsns Python
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
39 links | 25 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

8 medium 1 hard
10 solutions   October 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality