Number Of Corner Rectangles Problem
Description
LeetCode Problem 750.
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.
Example 1:

Input: grid = [[1,0,0,1,0],[0,0,1,0,1],[0,0,0,1,0],[1,0,1,0,1]]
Output: 1
Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].
Example 2:

Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 9
Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
Example 3:

Input: grid = [[1,1,1,1]]
Output: 0
Explanation: Rectangles must have four distinct corners.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 200grid[i][j]is either0or1.- The number of
1's in the grid is in the range[1, 6000].
Solution
Approach: Count Column Pairs Row by Row
A corner rectangle is fixed by choosing two rows and two columns such that all four crossing cells are 1. Look at it from the column side: if two columns i < j are both 1 in a row, that row can be the top or the bottom of a rectangle with any other row that also has 1s in both columns i and j.
So process the rows from top to bottom and keep pairs[i][j], the number of rows seen so far that have a 1 in both column i and column j. For the current row, list its 1 columns and go over every pair (i, j) of them:
- each of the
pairs[i][j]earlier rows forms exactly one new rectangle with this row, so addpairs[i][j]to the answer; - then increment
pairs[i][j], so later rows can pair with this one.
Every rectangle is counted exactly once, at its bottom row. A row with only one 1 (or a single row, as in example 3) adds no pairs, so it never creates a rectangle.
Only pairs of 1s in the same row cost time, which is what makes this fast: with at most 6000 ones in the grid, the work is bounded by the number of such pairs, not by looking at every choice of four cells.
Complexity: O(m · n2) time in the worst case (every row's pairs of 1 columns), and O(n2) extra space for pairs.
class Solution:
def countCornerRectangles(self, grid: List[List[int]]) -> int:
n = len(grid[0])
# pairs[i][j]: how many rows seen so far have a 1 in both column i and column j
pairs = [[0] * n for _ in range(n)]
ans = 0
for row in grid:
ones = [j for j in range(n) if row[j] == 1]
for a in range(len(ones)):
for b in range(a + 1, len(ones)):
i, j = ones[a], ones[b]
ans += pairs[i][j] # each earlier row with this pair closes one rectangle
pairs[i][j] += 1
return ans