Number Of Corner Rectangles - Problem
Corner Rectangle Counter Challenge

Imagine you're analyzing a digital grid pattern where certain cells are "active" (marked as 1) and others are "inactive" (marked as 0). Your task is to find all possible corner rectangles that can be formed using only the active cells.

A corner rectangle is formed by four distinct active cells (1's) that create the corners of an axis-aligned rectangle. The key insight is that only the corners need to be active - the cells inside or on the edges can be anything!

Goal: Count the total number of such corner rectangles in the given binary matrix.

Example: In a grid like:
[[1,0,1],
[0,0,0],
[1,0,1]]


The four corner 1's form exactly 1 corner rectangle.

Input & Output

example_1.py — Basic Rectangle
$ Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 1
💡 Note: There is exactly one corner rectangle formed by the four 1's at positions (0,0), (0,2), (2,0), and (2,2). The middle row and column can contain any values since only corners matter.
example_2.py — Multiple Rectangles
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 9
💡 Note: With all 1's, we can form multiple rectangles. For each pair of rows (3 pairs total), we have 3 common positions, giving us C(3,2) = 3 rectangles per pair. Total: 3 × 3 = 9 rectangles.
example_3.py — No Rectangles
$ Input: grid = [[1,0],[0,1]]
Output: 0
💡 Note: The 1's are positioned diagonally, so no axis-aligned rectangles can be formed. We need at least 2 rows and 2 columns with 1's at the intersections.

Visualization

Tap to expand
Corner Rectangle Formation101100001011Row 0 & Row 1: 3 common 1'sC(3,2) = 3×2/2 = 3 rectanglesRow 0 & Row 2: 3 common 1'sC(3,2) = 3×2/2 = 3 rectanglesRow 1 & Row 2: 3 common 1'sC(3,2) = 3×2/2 = 3 rectanglesTotal: 3 + 3 + 3 = 9 rectangles
Understanding the Visualization
1
Identify Corner Posts
Find all positions marked with 1 in the grid
2
Pair Up Rows
Take any two different rows and see where they both have posts
3
Count Frame Possibilities
With k matching post positions, you can build k×(k-1)/2 rectangular frames
4
Sum All Combinations
Add up rectangle counts from all possible row pairs
Key Takeaway
🎯 Key Insight: When two rows share k positions with 1's, they can form exactly k×(k-1)/2 corner rectangles together!

Time & Space Complexity

Time Complexity
⏱️
O(m²n)

For each of the m*(m-1)/2 row pairs, we scan n columns once

n
2n
Linear Growth
Space Complexity
O(1)

Only using variables to track column positions and counts

n
2n
Linear Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 200
  • grid[i][j] is either 0 or 1
  • The number of 1's in the grid is in the range [0, 6000]
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 15
28.4K Views
Medium Frequency
~18 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen