Right Triangles - Problem
๐บ Count Right Triangles in a Grid
You are given a 2D boolean matrix grid where each cell contains either 0 or 1. Your task is to count how many right triangles can be formed using cells with value 1.
A right triangle is formed by three cells with value 1 that satisfy this geometric property:
- One cell serves as the corner (right angle vertex)
- One cell shares the same row as the corner
- One cell shares the same column as the corner
Important: The three cells don't need to be adjacent to each other - they can be anywhere in their respective row/column as long as they form the right triangle pattern.
Goal: Return the total number of right triangles that can be formed.
Example visualization:
Grid: [[1,0,1], [0,1,0], [1,0,1]] Right triangle example: - Corner at (1,1) with value 1 - Row partner at (1,0) or (1,2) - but these are 0, so no triangle - Column partner at (0,1) or (2,1) - but these are 0, so no triangle
Input & Output
example_1.py โ Basic Grid
$
Input:
grid = [[0,1,0],[0,1,1],[0,1,0]]
โบ
Output:
2
๐ก Note:
There are 2 right triangles: Triangle 1 uses corner at (1,2) with row partner (1,1) and column partner (0,2). Triangle 2 uses corner at (1,1) with row partner (1,2) and column partner (2,1).
example_2.py โ Larger Grid
$
Input:
grid = [[1,0,0,0],[0,1,0,1],[1,0,0,0]]
โบ
Output:
0
๐ก Note:
No right triangles can be formed because no cell has both a row partner and column partner with value 1.
example_3.py โ All Ones
$
Input:
grid = [[1,1],[1,1]]
โบ
Output:
4
๐ก Note:
Each of the 4 cells can serve as a corner: (0,0) forms 1ร1=1 triangle, (0,1) forms 1ร1=1 triangle, (1,0) forms 1ร1=1 triangle, (1,1) forms 1ร1=1 triangle. Total: 4 triangles.
Constraints
- 1 โค m, n โค 1000 where m = grid.length and n = grid[i].length
- grid[i][j] is either 0 or 1
- The number of cells with value 1 is at most min(1000, m ร n)
Visualization
Tap to expand
Understanding the Visualization
1
Identify Corner
Select a cell with value 1 as the right-angle corner of potential triangles
2
Find Row Partners
Count other cells with value 1 in the same row as potential horizontal vertices
3
Find Column Partners
Count other cells with value 1 in the same column as potential vertical vertices
4
Calculate Triangles
Multiply row partners by column partners to get total triangles for this corner
Key Takeaway
๐ฏ Key Insight: Every cell with value 1 can be a corner, and the number of right triangles it creates equals the product of other 1s in its row and column.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code