#3128
Right Triangles
MediumArrayHash TableMathCombinatoricsCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all combinations, we can count the number of 1s in each row and column. For each 1 found, the number of right triangles it can form is determined by the counts of 1s in its row and column.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of 1s in each row and each column.
- 2Step 2: For each cell that contains a 1, calculate the potential triangles it can form using the formula: (rowCount - 1) * (colCount - 1).
- 3Step 3: Sum these values to get the total number of right triangles.
solution.py20 lines
1# Full working Python code
2
3def count_right_triangles(grid):
4 rows = [0] * len(grid)
5 cols = [0] * len(grid[0])
6 count = 0
7
8 for i in range(len(grid)):
9 for j in range(len(grid[0])):
10 if grid[i][j] == 1:
11 rows[i] += 1
12 cols[j] += 1
13
14 for i in range(len(grid)):
15 for j in range(len(grid[0])):
16 if grid[i][j] == 1:
17 count += (rows[i] - 1) * (cols[j] - 1)
18
19 return count
20ℹ
Complexity note: The time complexity is O(n) because we are iterating through the grid a couple of times, and the space complexity is O(n) due to the additional arrays for row and column counts.
- 1The right triangle can be formed by ensuring one element is in the same row as another and in the same column as the third.
- 2Counting the number of 1s in rows and columns allows us to efficiently calculate potential triangles.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.