LeetCode 750: Number Of Corner Rectangles Solution

Master LeetCode problem 750 (Number Of Corner Rectangles), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

750. Number Of Corner Rectangles

Problem Explanation

Explanation:

To solve this problem, we can iterate through each pair of rows in the given grid and count the number of pairs of columns that have 1s in the same positions in both rows. For each pair of rows, if we have n 1s in common between the columns of those two rows, we can form n * (n-1) / 2 corner rectangles.

Here are the detailed steps:

  1. Initialize a variable total to keep track of the total number of corner rectangles.
  2. Iterate through each pair of rows i and j in the grid.
  3. For each pair of rows, iterate through each pair of columns c1 and c2.
  4. If both grid[i][c1] and grid[j][c1] are 1, and grid[i][c2] and grid[j][c2] are also 1, increment the total by 1.
  5. Finally, return the total number of corner rectangles.

The time complexity of this solution is O(m^2 * n) where m is the number of rows and n is the number of columns in the grid. The space complexity is O(1).

:

Solution Code

class Solution {
    public int countCornerRectangles(int[][] grid) {
        int total = 0;
        for (int i = 0; i < grid.length - 1; i++) {
            for (int j = i + 1; j < grid.length; j++) {
                int count = 0;
                for (int c = 0; c < grid[0].length; c++) {
                    if (grid[i][c] == 1 && grid[j][c] == 1) {
                        count++;
                    }
                }
                total += count * (count - 1) / 2;
            }
        }
        return total;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 750 (Number Of Corner Rectangles)?

This page provides optimized solutions for LeetCode problem 750 (Number Of Corner Rectangles) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 750 (Number Of Corner Rectangles)?

The time complexity for LeetCode 750 (Number Of Corner Rectangles) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 750 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 750 in Java, C++, or Python.

Back to LeetCode Solutions