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())
Difficulty
and has an acceptance rate of about 56% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 417: Pacific Atlantic Water Flow
- problem 442: Find All Duplicates in an Array
- problem 457: Circular Array Loop
- problem 565: Array Nesting
- problem 647: Palindromic Substrings
- problem 721: Accounts Merge
- problem 785: Is Graph Bipartite?
- problem 1061: Lexicographically Smallest Equivalent String
- problem 273: Integer to English Words
Extra
- 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