Python 1727.py
class Solution:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
result = 0
height = len(matrix)
width = len(matrix[0])
# vertical prefix sum with reset if zero
prefix = [ 0 ] * width
# best horizontal combo
for y in range(height):
for x, bit in enumerate(matrix[y]):
prefix[x] += 1
prefix[x] *= bit # keeps value or resets to zero
for dx, dy in enumerate(sorted(prefix, reverse = True), start = 1):
result = max(result, dx * dy)
return result
Difficulty
and has an acceptance rate of about 78% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Matrix
- Sorting
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 Solution.largestSubmatrix method computes the area of the largest sub-matrix consisting solely of 1s in a binary matrix. It processes the input row by row, maintaining a vertical running count of consecutive 1s for each column. After updating this count for a given row, the method sorts the column heights in descending order and evaluates every possible width, updating the best area found so far. The final result is the maximal rectangle area that can be formed by contiguous columns and rows of 1s.
Core Logic
Initialization
result = 0
height = len(matrix)
width = len(matrix[0])
prefix = [0] * width
result stores the best area discovered. height and width capture the matrix dimensions. The prefix list holds, for each column, the number of consecutive 1s ending at the current row.
Updating Column Heights
for y in range(height):
for x, bit in enumerate(matrix[y]):
prefix[x] += 1
prefix[x] *= bit
For each cell, the code first increments the column counter, then multiplies by the cell value (bit). When bit is 1, the incremented count is retained; when bit is 0, the multiplication forces the counter back to 0. This compact expression simultaneously updates the height and resets it on encountering a zero, eliminating the need for an explicit conditional branch.
Evaluating Horizontal Combinations
for dx, dy in enumerate(sorted(prefix, reverse=True), start=1):
result = max(result, dx * dy)
After the column heights for the current row are prepared, they are sorted in descending order. The sorted list represents the tallest possible columns that can be paired with any width. The loop iterates over each possible width dx (starting at 1) and the corresponding height dy (the dx-th largest column height). Multiplying dx and dy yields the area of a rectangle that uses the dx widest set of columns with at least dy rows of 1s. The maximum of these products updates result.
Final Return
return result
When all rows have been processed, result holds the area of the largest all-1 sub-matrix.
Edge Cases Handled
The algorithm gracefully handles matrices that consist entirely of zeros; the prefix array remains zero throughout, and the sorted list yields only zeros, so result stays at its initial value of 0.
When the matrix contains a single row, the inner update loop builds a prefix that mirrors the row itself, and the sorting step evaluates every possible contiguous segment of 1s, correctly identifying the longest run.
A single column matrix is treated similarly: the prefix list has length one, and the sorted list contains a single height value that grows with consecutive 1s, allowing the algorithm to capture the full vertical stretch.
Matrices that are fully filled with 1s produce a prefix that increments uniformly each row; sorting does not change the order, and the area calculation yields the product of the full height and width, which is the correct maximal rectangle.
Rows that contain interleaved zeros and ones cause the multiplication step to reset the affected column counters, ensuring that only uninterrupted vertical runs contribute to subsequent area calculations.
Performance Optimizations
The code leverages an in-place update of the prefix array using arithmetic (+= followed by *=) to avoid explicit branching for zero detection, which reduces branch misprediction overhead on modern CPUs.
Sorting the column heights for each row enables the algorithm to consider the best possible height for any given width without enumerating all column subsets. By sorting once per row and then scanning the sorted list, the method computes the maximal area for that row in linear time relative to the number of columns, avoiding nested loops over column pairs.
The use of a single result variable updated via max eliminates the need for auxiliary data structures to track intermediate best areas, keeping the memory footprint minimal.
Overall, the combination of a compact vertical prefix update, per-row sorting, and a single pass over the sorted heights yields an efficient solution that scales well with both matrix dimensions.
ELI5 - Simplified Explanation
Imagine a big grid made of squares that are either empty or filled with building blocks. The goal is to find the biggest rectangle you can build using only the blocks.
First, look at the grid one row at a time while keeping track of how many blocks are stacked up in each column. Think of this like building a tower in every spot. If there is a floor with no block, the tower in that spot must fall down and start over from nothing.
After updating the tower heights for the current row, sort those heights from tallest to shortest. This helps see how many blocks can fit together in a flat, wide rectangle. By checking each possible width and seeing what the shortest tower in that group is, it becomes easy to find the largest area you can make. The process repeats for every level of the grid, slowly finding the best spot to build the largest space possible.
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | C# | Go | Python | Rust | TS | ||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 695: Max Area of Island
Solved On The Same Day
- problem 3079: Find the Sum of Encrypted Integers
- problem 1111: Maximum Nesting Depth of Two Valid Parentheses Strings
- problem 1806: Minimum Number of Operations to Reinitialize a Permutation
- problem 2186: Minimum Number of Steps to Make Two Strings Anagram II
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