Leetcode 3128: Right Triangles

grid47
grid47
Exploring patterns and algorithms
Dec 30, 2023 6 min read

You are given a 2D binary matrix grid, where each element is either 0 or 1. A collection of three elements of the grid is considered a right triangle if one element lies in the same row as another and in the same column as the third. The three elements must not be adjacent to each other. Your task is to count the number of right triangles that can be formed where all three elements have a value of 1.
Problem
Approach
Steps
Complexity
Input: The input is a 2D binary matrix grid of size m x n, where each element is either 0 or 1.
Example: Example 1: Input: grid = [[0, 1, 0], [0, 1, 1], [0, 1, 0]] Example 2: Input: grid = [[1, 0, 0, 0], [0, 1, 0, 1], [1, 0, 0, 0]]
Constraints:
• 1 <= grid.length <= 1000
• 1 <= grid[i].length <= 1000
• 0 <= grid[i][j] <= 1
Output: Return the total number of right triangles that can be formed using the 1's in the grid.
Example: Example 1: Output: 2 Example 2: Output: 0
Constraints:
Goal: To count all possible right triangles formed by the 1's in the grid.
Steps:
• Use dynamic programming to count the number of 1's in the row and column directions for each cell.
• Iterate through each cell and check if it can form a right triangle with other cells in the same row and column that contain 1's.
Goal: The size of the matrix grid can be as large as 1000x1000.
Steps:
• 1 <= grid.length <= 1000
• 1 <= grid[i].length <= 1000
• The values in the grid are either 0 or 1.
Assumptions:
• The input matrix is always a valid 2D binary grid.
Input: Example 1
Explanation: In this case, the two right triangles that can be formed have all 1's as their elements. These two right triangles are formed from grid positions that satisfy the condition of a right triangle.

Input: Example 2
Explanation: Here, there are no possible right triangles because no three elements form a valid right triangle.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus