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:
2
💡 Note:
Two right triangles can be formed: (0,0)→(0,2)→(1,2) and (0,0)→(0,2)→(2,2). Each forms an L-shape with one vertex sharing row with another and column with the third.
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:
6
💡 Note:
With all cells being 1, many L-shaped triangles are possible. Each corner cell can form triangles with pairs from its row and column.
Constraints
- 1 ≤ grid.length ≤ 1000
- 1 ≤ grid[i].length ≤ 1000
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
2D boolean matrix with 1s and 0s
2
Find L-Shapes
Identify right triangles formed by three 1s
3
Count Total
Return total number of valid triangles
Key Takeaway
🎯 Key Insight: For each 1 as corner, multiply (remaining 1s in row) × (remaining 1s in column)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code