Count Square Submatrices with All Ones
Problem Statement
You get a grid of 0s and 1s. Count the square blocks inside the grid that are filled only with 1s.
Every size counts. A single 1 is a square of side 1. A 2 × 2 block of ones is a square of side 2, and it counts on top of the four single ones inside it.
A grid matrix with m rows and n columns. Each cell is 0 or 1.
The number of all-ones square blocks, counting every side length.
There are 10 squares of side 1, 4 squares of side 2 and 1 square of side 3. The total is 10 + 4 + 1 = 15.
There are 6 squares of side 1. There is 1 square of side 2, the block at rows 1–2 and columns 0–1. The total is 6 + 1 = 7.
- • 1 ≤ m, n ≤ 300
- • Each cell is 0 or 1.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Try every top-left corner and every side, and check every cell of each square
Count the ones in a square with a prefix-sum table; the square counts when the count is k × k
dp[r][c] = squares that end at (r, c); add every dp value to the total
A square is fixed by its top-left corner and its side k. Try every corner and every side that fits. For each one, check every cell of the square. If all of them are 1, add one to the count.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Grid translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.