{x}
blog image

Number Of Corner Rectangles

Solution Explanation: Counting Corner Rectangles

The problem asks to find the number of corner rectangles in a binary matrix (a matrix containing only 0s and 1s). A corner rectangle is defined as a rectangle formed by four distinct 1s at the corners.

Approach: Hash Table + Enumeration

This approach efficiently counts corner rectangles by iterating through the matrix rows and leveraging a hash table (or map) to store and retrieve counts.

  1. Iteration: The code iterates through each row of the input matrix grid.

  2. Inner Loop: For each row, nested loops iterate through all pairs of columns (i, j) where i < j. This ensures we only consider pairs of columns once and avoids duplicates.

  3. Corner Check: Inside the inner loop, it checks if both grid[row][i] and grid[row][j] are 1. This means we've found two potential corners of a rectangle on the same row.

  4. Hash Table Lookup: If both columns contain a 1, the code checks a hash table (e.g., cnt in Python, cnt in Java, cnt in C++, cnt in Go, cnt in TypeScript). This table stores the number of times a specific pair of columns (i, j) has appeared with a 1 in previous rows. The number stored represents the number of rows already found that complete a rectangle with the current row.

  5. Counting Rectangles: The count from the hash table (cnt[(i, j)]) is added to the total count of rectangles (ans).

  6. Hash Table Update: After adding the count, the entry for the column pair (i, j) in the hash table is incremented (cnt[(i, j)] += 1). This reflects that the current row also contains 1s in columns i and j.

  7. Return: Finally, the function returns the total count of corner rectangles (ans).

Time and Space Complexity Analysis

  • Time Complexity: O(m * n^2), where 'm' is the number of rows and 'n' is the number of columns in the matrix. The outer loop iterates through rows (m times), and the nested loops iterate through column pairs (approximately n^2/2 times). The hash table lookups and updates are typically O(1) on average.

  • Space Complexity: O(n^2), which is the space needed to store the hash table. The maximum number of unique column pairs is n*(n-1)/2, approximately O(n^2).

Code Examples (with explanations inline)

The code examples in Python, Java, C++, Go, and TypeScript provided in the original response demonstrate this approach. The comments in the code provide explanations of the different steps. I will not repeat them here, as they are already well-explained in the original response. The core logic is the same across all languages, differing only in syntax and data structure implementations.