28. Find Rectangle with Corners as 1
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given an n ร m
binary matrix mat[][]
containing only 0
s and 1
s, determine if there exists a rectangle within the matrix such that all four corners of the rectangle are 1
. If such a rectangle exists, return true
; otherwise, return false
.
๐ Examples
Example 1:
Input:
mat = [
[1, 0, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 1]
]
Output:
true
Explanation:
Valid corners at (1,2), (1,4), (3,2), (3,4)
.
Example 2:
Input:
mat = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
Output:
false
Explanation:
No four 1
s form the corners of a rectangle.
๐ Constraints
1 โค n, m โค 200
mat[i][j] โ {0, 1}
โ
My Approach
Row Pair Comparison with Column Counting
Goal: Check if any two rows in the matrix have at least two common columns with value 1
. Such a pair would form the top-left, top-right, bottom-left, and bottom-right corners of a rectangle with 1s.
Algorithm Steps:
Let
n
be the number of rows andm
be the number of columns in the matrix.Iterate over all pairs of rows
(i, j)
wherei < j
:For each column
k
, check if bothmat[i][k]
andmat[j][k]
are1
.Count the number of such columns.
If the count exceeds 1, return
true
(a rectangle exists).
If no such pair of rows with 2 or more common 1s exists, return
false
.
This brute-force check across all row pairs is efficient enough for moderate matrix sizes due to n(n-1)/2
row combinations and m
column checks per combination.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(nยฒยทm), as we compare each pair of
n
rows and checkm
columns.Expected Auxiliary Space Complexity: O(1), as we use only constant extra variables.
๐ง Code (C++)
class Solution {
public:
bool ValidCorner(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) {
int cnt = 0;
for (int k = 0; k < m; ++k)
cnt += mat[i][k] & mat[j][k];
if (cnt > 1) return true;
}
return false;
}
};
๐งโ๐ป Code (Java)
class Solution {
public boolean ValidCorner(int[][] mat) {
int n = mat.length, m = mat[0].length;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int cnt = 0;
for (int k = 0; k < m; k++)
cnt += mat[i][k] & mat[j][k];
if (cnt > 1) return true;
}
return false;
}
}
๐ Code (Python)
class Solution:
def ValidCorner(self, mat):
n, m = len(mat), len(mat[0])
for i in range(n):
for j in range(i + 1, n):
if sum(mat[i][k] & mat[j][k] for k in range(m)) > 1:
return True
return False
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated