Right Triangles Problem
Description
LeetCode Problem 3128.
You are given a 2D boolean matrix grid.
A collection of 3 elements of grid is a right triangle if one of its elements is in the same row with another element and in the same column with the third element. The 3 elements may not be next to each other.
Return an integer that is the number of right triangles that can be made with 3 elements of grid such that all of them have a value of 1.
Example 1:
| 0 | 1 | 0 |
|---|---|---|
| 0 | 1 | 1 |
| 0 | 1 | 0 |
| 0 | 1 | 0 |
|---|---|---|
| 0 | 1 | 1 |
| 0 | 1 | 0 |
| 0 | 1 | 0 |
|---|---|---|
| 0 | 1 | 1 |
| 0 | 1 | 0 |
Input: grid = [[0,1,0],[0,1,1],[0,1,0]]
Output: 2
Explanation:
There are two right triangles with elements of the value 1. Notice that the blue ones do not form a right triangle because the 3 elements are in the same column.
Example 2:
| 1 | 0 | 0 | 0 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 0 |
Input: grid = [[1,0,0,0],[0,1,0,1],[1,0,0,0]]
Output: 0
Explanation:
There are no right triangles with elements of the value 1. Notice that the blue ones do not form a right triangle.
Example 3:
| 1 | 0 | 1 |
|---|---|---|
| 1 | 0 | 0 |
| 1 | 0 | 0 |
| 1 | 0 | 1 |
|---|---|---|
| 1 | 0 | 0 |
| 1 | 0 | 0 |
Input: grid = [[1,0,1],[1,0,0],[1,0,0]]
Output: 2
Explanation:
There are two right triangles with elements of the value 1.
Constraints:
1 <= grid.length <= 10001 <= grid[i].length <= 10000 <= grid[i][j] <= 1
Solution
Approach: Counting + Enumeration
Count the 1s in every row (rows) and every column (cols).
Treat each 1 at (i, j) as the right-angle corner. The other two corners must be another 1 in the same row and another 1 in the same column, which gives (rows[i] - 1) * (cols[j] - 1) triangles. Sum this over all 1s.
Complexity: O(mn) time and O(m + n) space.
class Solution:
def numberOfRightTriangles(self, grid: List[List[int]]) -> int:
rows = [0] * len(grid)
cols = [0] * len(grid[0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
rows[i] += x
cols[j] += x
ans = 0
for i, row in enumerate(grid):
for j, x in enumerate(row):
if x:
ans += (rows[i] - 1) * (cols[j] - 1)
return ans