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 0s and 1s, 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 1s 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:

  1. Let n be the number of rows and m be the number of columns in the matrix.

  2. Iterate over all pairs of rows (i, j) where i < j:

    • For each column k, check if both mat[i][k] and mat[j][k] are 1.

    • Count the number of such columns.

    • If the count exceeds 1, return true (a rectangle exists).

  3. 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 check m 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;
    }
};
โšก Alternative Approaches

๐Ÿ“Š 2๏ธโƒฃ Bitset Intersection (Fast for Sparse Matrices)

Algorithm Steps:

  1. Convert each row to a bitset of size m.

  2. For each pair of rows, compute bitset[i] & bitset[j].

  3. If the result has .count() > 1, a rectangle exists.

class Solution {
  public:
    bool ValidCorner(vector<vector<int>>& mat) {
        int n = mat.size(), m = mat[0].size();
        vector<bitset<1000>> bs(n);
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < m; ++j)
                if (mat[i][j]) bs[i].set(j);
        for (int i = 0; i < n; ++i)
            for (int j = i + 1; j < n; ++j)
                if ((bs[i] & bs[j]).count() > 1) return true;
        return false;
    }
};

โœ… Why This Works Well?

  • Uses hardware-optimized operations for fast intersection.

  • Best when m is large and rows are sparse.

๐Ÿ“ Complexity Analysis:

  • Time: O(nยฒยท(m/64))

  • Space: O(nยทm/64) for storing bitsets

๐Ÿ“Š 3๏ธโƒฃ Column-Pair Counting (Best for Dense Rows)

Algorithm Steps:

  1. For each row, collect all 1-column indices.

  2. For every pair of columns (a,b) in that row, encode a 64-bit key: (a<<32)|b.

  3. Use a map to count how often each column pair appears.

  4. If any pair appears in more than 1 row โ†’ rectangle exists.

class Solution {
  public:
    bool ValidCorner(vector<vector<int>>& mat) {
        int m = mat[0].size();
        unordered_map<long long, int> count;
        for (auto& row : mat) {
            vector<int> ones;
            for (int j = 0; j < m; ++j)
                if (row[j]) ones.push_back(j);
            for (int a = 0; a < ones.size(); ++a)
                for (int b = a + 1; b < ones.size(); ++b) {
                    long long key = ((long long)ones[a] << 32) | ones[b];
                    if (++count[key] > 1) return true;
                }
        }
        return false;
    }
};

โœ… Why This Works Well?

  • Converts the 2D problem to a 1D hash-detection task.

  • Early exit when duplicate column-pairs found.

๐Ÿ“ Complexity Analysis:

  • Time: O(nยทkยฒ) where k is average number of 1s per row.

  • Space: O(nยทkยฒ) for the map

๐Ÿ†š Comparison of Approaches

Approach

โฑ๏ธ Time

๐Ÿ—‚๏ธ Space

โœ… Pros

โš ๏ธ Cons

โ–ถ๏ธ Row Pair & Column Count

๐Ÿ”ธ O(nยฒยทm)

๐ŸŸข O(1)

Simple and intuitive

Slow for large n

๐Ÿงฎ Bitset Intersection

๐ŸŸข O(nยฒยท(m/64))

๐ŸŸก O(nยทm/64)

Fast with sparse rows, scalable

Needs bitset and fixed size

๐Ÿ”— Column Pair Map

๐ŸŸข O(nยทkยฒ)

๐ŸŸก O(nยทkยฒ)

Best for sparse 1s, fast hash check

Costly if rows are densely filled

โœ… Best Choice?

Scenario

Recommended Approach

๐Ÿ† Matrix is small or simple

๐Ÿฅ‡ Row Comparison

๐Ÿ“ Large m with sparse 1s

๐Ÿฅˆ Bitset Intersection

โš™๏ธ Large matrix with many rows

๐Ÿฅ‰ Column Pair Mapping

๐Ÿง‘โ€๐Ÿ’ป 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