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
Right Triangles - Counting Approach INPUT 2D Boolean Matrix Grid 1 0 1 0 1 1 0 1 1 r0 r1 r2 c0 c1 c2 grid = [[1,0,1], [0,1,1], [0,1,1]] ALGORITHM STEPS 1 Count 1s per Row/Col rowCount = [2, 2, 2] colCount = [1, 3, 3] 2 For each cell = 1 Cell is corner of triangle 3 Calculate triangles (rowCnt-1) * (colCnt-1) 4 Sum all contributions Add to total count Cell Contributions: (0,0): (2-1)*(1-1) = 0 (0,2): (2-1)*(3-1) = 2 (1,1): (2-1)*(3-1) = 2 (1,2): (2-1)*(3-1) = 2 (2,1): (2-1)*(3-1) = 2 (2,2): (2-1)*(3-1) = 2 FINAL RESULT Valid Right Triangles Found Triangle 1 1 1 1 Triangle 2 1 1 1 OUTPUT 2 OK - 2 right triangles Key Insight: For each cell with value 1, it can be the corner vertex of a right triangle. The number of triangles with corner at (i,j) = (row1s - 1) * (col1s - 1) Time: O(m*n) - single pass after counting. Space: O(m+n) for row/col counts. TutorialsPoint - Right Triangles | Optimized - Count Row/Column 1s
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen