751. Number Of Corner Rectangles
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
The problem asks us to find the number of axis-aligned rectangles formed by four '1's in a grid. A brute-force approach of checking every possible set of four '1's would be too slow. We need a more efficient way to count these rectangles.
Solution
Number Of Corner Rectangles in Python
class Solution:
def countCornerRectangles(self, grid: List[List[int]]) -> int:
m = len(grid)
if m < 2:
return 0
n = len(grid[0])
if n < 2:
return 0
# Use a dictionary to store counts of column pairs.
# Key: tuple (c1, c2), Value: count of rows.
count = {}
ans = 0
for r in range(m):
# For the current row, find all columns with a '1'.
ones = []
for c in range(n):
if grid[r][c] == 1:
ones.append(c)
# Iterate through all pairs of '1's in the current row.
for i in range(len(ones)):
for j in range(i + 1, len(ones)):
c1, c2 = ones[i], ones[j]
# The pair of columns (c1, c2) forms a key.
# Get the number of previous rows that had '1's at this column pair.
prev_count = count.get((c1, c2), 0)
# Add to the total number of rectangles.
ans += prev_count
# Update the count for this pair to include the current row.
count[(c1, c2)] = prev_count + 1
return ans
Number Of Corner Rectangles in Java
class Solution {
public int countCornerRectangles(int[][] grid) {
int m = grid.length;
if (m < 2) return 0;
int n = grid[0].length;
if (n < 2) return 0;
// Use a map to store counts of column pairs.
// Key: encoded column pair, Value: count of rows.
// Encoding: c1 * n + c2
Map<Integer, Integer> count = new HashMap<>();
int ans = 0;
for (int r = 0; r < m; r++) {
// For the current row, find all columns with a '1'.
List<Integer> ones = new ArrayList<>();
for (int c = 0; c < n; c++) {
if (grid[r][c] == 1) {
ones.add(c);
}
}
// Iterate through all pairs of '1's in the current row.
for (int i = 0; i < ones.size(); i++) {
for (int j = i + 1; j < ones.size(); j++) {
int c1 = ones.get(i);
int c2 = ones.get(j);
// Encode the pair of columns into a single key.
int key = c1 * n + c2;
// Get the number of previous rows that had '1's at this column pair.
int prevCount = count.getOrDefault(key, 0);
// Add to the total number of rectangles.
ans += prevCount;
// Update the count for this pair to include the current row.
count.put(key, prevCount + 1);
}
}
}
return ans;
}
}
Number Of Corner Rectangles in C++
class Solution {
public:
int countCornerRectangles(vector<vector<int>>& grid) {
int m = grid.size();
if (m < 2) return 0;
int n = grid[0].size();
if (n < 2) return 0;
// Use a map to store counts of column pairs.
// The key is an encoding of the column pair (c1, c2).
// A simple encoding: c1 * n + c2 (since c1 < c2 < n).
unordered_map<int, int> count;
int ans = 0;
for (int r = 0; r < m; ++r) {
// For the current row, find all columns with a '1'.
vector<int> ones;
for (int c = 0; c < n; ++c) {
if (grid[r][c] == 1) {
ones.push_back(c);
}
}
// Iterate through all pairs of '1's in the current row.
for (int i = 0; i < ones.size(); ++i) {
for (int j = i + 1; j < ones.size(); ++j) {
int c1 = ones[i];
int c2 = ones[j];
// Encode the pair of columns into a single key.
int key = c1 * n + c2;
// If this pair has been seen before, it forms new rectangles.
// The number of new rectangles is the number of times we've seen this pair.
if (count.count(key)) {
ans += count[key];
}
// Increment the count for this pair for the current row.
count[key]++;
}
}
}
return ans;
}
};
Number Of Corner Rectangles in TypeScript
function countCornerRectangles(grid: number[][]): number {
const m = grid.length;
if (m < 2) return 0;
const n = grid[0].length;
if (n < 2) return 0;
// Use a Map to store counts of column pairs.
// Key: encoded column pair, Value: count of rows.
// Encoding: c1 * n + c2
const count = new Map<number, number>();
let ans = 0;
for (let r = 0; r < m; r++) {
// For the current row, find all columns with a '1'.
const ones: number[] = [];
for (let c = 0; c < n; c++) {
if (grid[r][c] === 1) {
ones.push(c);
}
}
// Iterate through all pairs of '1's in the current row.
for (let i = 0; i < ones.length; i++) {
for (let j = i + 1; j < ones.length; j++) {
const c1 = ones[i];
const c2 = ones[j];
// Encode the pair of columns into a single key.
const key = c1 * n + c2;
// Get the number of previous rows that had '1's at this column pair.
const prevCount = count.get(key) || 0;
// Add to the total number of rectangles.
ans += prevCount;
// Update the count for this pair to include the current row.
count.set(key, prevCount + 1);
}
}
}
return ans;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.