Right Triangles - Problem
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.
Input & Output
Example 1 — Basic Grid
$
Input:
grid = [[1,0,1],[0,1,1],[0,1,1]]
›
Output:
8
💡 Note:
There are 8 possible right triangles. For each cell with value 1, we count how many triangles can be formed with that cell as the corner of the L-shape by multiplying the number of other 1s in its row with the number of other 1s in its column.
Example 2 — No Triangles
$
Input:
grid = [[1,0,0],[0,1,0],[0,0,1]]
›
Output:
0
💡 Note:
No three 1s can form a right triangle because no cell shares both a row and column with two other cells containing 1s.
Example 3 — Multiple Triangles
$
Input:
grid = [[1,1,1],[1,1,1]]
›
Output:
12
💡 Note:
With all cells being 1, each cell can form multiple L-shaped triangles. Each corner cell can form triangles by choosing one cell from its row and one from its column, giving (row_count-1) × (col_count-1) triangles per corner.
Constraints
- 1 ≤ grid.length ≤ 1000
- 1 ≤ grid[i].length ≤ 1000
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code