Problem 1504

Abstract / Summary

Count all rectangles in a binary matrix that contain only ones.

Note

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

Python 1504.py

class Solution:
    def numSubmat(self, mat: List[List[int]]) -> int:
        result = 0
        height = len(mat)
        width  = len(mat[0])

        ones = [ 0 ] * width
        for row in mat:
            # consecutive ones (horizontal)
            for x, cell in enumerate(row):
                ones[x] += cell
                ones[x] *= cell # reset if 0, keep if 1

            low = []
            sub = [ 0 ] * width
            for x, count in enumerate(ones):
                # keep track of lowest number and its index
                while low and ones[low[-1]] >= count:
                    low.pop()

                if low:
                    start  = low[-1]
                    length = x - start
                    sub[x] = sub[start] + count * length
                else:
                    sub[x] = count * (x + 1)

                low.append(x)

            result += sum(sub)

        return result
32 lines | 959 bytes | submitted July 20, 2024 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Matrix
  • Monotonic Stack
  • Stack
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 numSubmat method computes the total number of sub-matrices that consist entirely of 1s in a binary matrix mat. It processes the matrix row by row, building a histogram of consecutive 1s in each column and then uses a monotonic stack to efficiently count the sub-matrices that end at the current row. The accumulated count is returned as the final result.

Key Steps

Initialization

The algorithm starts by preparing counters and dimensions.

result = 0
height = len(mat)
width  = len(mat[0])
ones = [0] * width

result holds the running total, height and width store the matrix size, and ones is a list that will store the height of the vertical streak of 1s for each column.

Updating the vertical histogram

For each row the code updates ones to reflect the number of consecutive 1s ending at the current row for every column.

for row in mat:
    for x, cell in enumerate(row):
        ones[x] += cell
        ones[x] *= cell   # resets to 0 when cell is 0, otherwise keeps the count

The addition accumulates the count, while the multiplication by cell (which is either 0 or 1) instantly resets the entry to 0 when a 0 is encountered, preserving the count only when the cell is 1.

Monotonic stack processing

A stack named low maintains indices of columns with strictly increasing heights in ones. This structure enables the algorithm to determine, for each column, the nearest column to the left that has a smaller height.

low = []
sub = [0] * width
for x, count in enumerate(ones):
    while low and ones[low[-1]] >= count:
        low.pop()

    if low:
        start  = low[-1]
        length = x - start
        sub[x] = sub[start] + count * length
    else:
        sub[x] = count * (x + 1)

    low.append(x)

If the stack is not empty, start points to the previous column with a lower height. The number of new sub-matrices contributed by column x is derived from the previously computed value sub[start] plus the product of the current height count and the width length of the region where this height is the minimum. When the stack is empty, the current column can extend back to the first column, so the contribution is simply count * (x + 1).

Accumulating the row contribution

After processing all columns for the current row, the contributions stored in sub are summed and added to the global result.

result += sum(sub)

The loop then proceeds to the next row, reusing the same ones, low, and sub structures.

Final return

When all rows have been processed, the method returns the accumulated count.

return result

Edge Cases Handled

The multiplication step ones[x] *= cell guarantees that any column encountering a 0 immediately resets its height to 0. Consequently, rows that contain only 0s contribute nothing to the final count, and the algorithm correctly handles matrices that are entirely 0s.

When a row consists solely of 1s, the histogram heights increase monotonically, and the monotonic stack never discards an index, allowing the algorithm to count every possible sub-matrix ending at that row.

The use of low as a stack of indices ensures that columns with equal heights are treated consistently: the while condition ones[low[-1]] >= count removes previous columns with the same height, so the leftmost occurrence becomes the reference point. This behavior correctly accounts for overlapping sub-matrices where the minimum height repeats.

Performance Optimizations

The solution reuses the ones list across rows, updating it in place rather than allocating a new histogram for each row. The reset-by-multiplication trick eliminates a conditional branch, making the update step both concise and fast.

The monotonic stack approach reduces the inner counting loop to amortized constant time per column, avoiding a nested iteration over all previous columns. By storing intermediate results in the sub array, the algorithm reuses previously computed contributions, preventing redundant calculations.

Summing the sub array with Python’s built-in sum leverages a highly optimized C implementation, further speeding up the aggregation of each row’s contribution. The overall memory footprint stays limited to a few auxiliary arrays of length equal to the matrix width, regardless of the matrix height.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant grid that looks like a dance floor covered in square tiles. Some tiles are lit up with bright lights, and some tiles are dark. This code is a clever helper that walks through every single row of this grid to find all the different shapes made of only the lit-up tiles.

First, the helper looks at the grid row by row. As it moves down, it keeps track of how many lit-up tiles are stacked on top of each other in a straight line going up. If a tile is dark, the stack count for that spot goes back to zero, but if it is lit, the stack grows taller.

Next, for each row, the computer builds a little collection of information. It looks at the height of the stacks of lights side by side. By using a special list to remember which stacks are shorter, it figures out how many little rectangular boxes of lights can be drawn starting at each spot. It does this by seeing how far it can stretch to the left while keeping the rectangles solid and filled with light.

As it processes each row, it adds up all the different rectangle combinations it finds. By the time it finishes checking the bottom row, it has counted every single possible rectangular shape of lights hidden within the grid. It acts like a busy counter, carefully keeping tabs on every single bright spot group it discovers while marching across the entire floor.

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 = 7 | μ = 7.15 | σ = 1.65

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ JS Java Python Go Rust TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
FelixFan1122 C#
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
30 links | 17 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   July 20, 2024

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