Number Of Corner Rectangles - Problem

Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles.

A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1's used must be distinct.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [[1,0,0,1],[0,0,1,0],[0,0,1,0]]
Output: 0
💡 Note: There are no corner rectangles. Row pairs (0,1), (0,2) have no common columns with 1's, and row pair (1,2) only has 1 common column with 1's (need at least 2).
Example 2 — Multiple Rectangles
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 9
💡 Note: Each pair of rows has 3 common columns with 1's. For each of 3 row pairs: C(3,2) = 3 rectangles. Total: 3 × 3 = 9 rectangles.
Example 3 — No Rectangles
$ Input: grid = [[1,0],[0,1]]
Output: 0
💡 Note: Only one pair of rows (0,1), but no columns have 1's in both rows, so no rectangles can be formed.

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 [1, 6000]

Visualization

Tap to expand
Corner Rectangles - Row Pair Optimization INPUT m x n grid (0s and 1s) 1 0 0 1 0 0 1 0 0 0 1 0 col 0 col 1 col 2 col 3 r0 r1 r2 Input Values: grid = [ [1,0,0,1], [0,0,1,0], [0,0,1,0] ] ALGORITHM STEPS 1 Iterate Row Pairs For each pair (r1, r2) where r1 < r2 2 Count Common 1s Find columns where both rows have value 1 3 Calculate Pairs If count = c, add c*(c-1)/2 rectangles 4 Sum All Results Accumulate total count Row Pair Analysis Pair(0,1): col match = 0 Pair(0,2): col match = 0 Pair(1,2): col match = 1 (only col 2 - not enough) Row 0: cols 0,3 both = 1 FINAL RESULT Found Corner Rectangle: 1 0 0 1 0 0 1 0 0 0 1 0 Row 0: corners at (0,0) and (0,3) Only 1 row pair has 2+ common 1s OUTPUT 1 OK - 1 Corner Rectangle Key Insight: Instead of checking all 4-corner combinations O(m^2 * n^2), optimize by iterating row pairs O(m^2). For each pair, count columns with 1s in both rows. If count=c, rectangles = c*(c-1)/2 (choosing 2 columns). Time: O(m^2 * n) | Space: O(1) - significant improvement over brute force approach. TutorialsPoint - Number Of Corner Rectangles | Row Pair Optimization Approach
Asked in
Google 15 Facebook 12 Amazon 8
18.5K Views
Medium Frequency
~25 min Avg. Time
456 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