#2732
Find a Good Subset of the Matrix
HardArrayHash TableBit ManipulationMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the insight that we only need to check for rows with all zeros or pairs of rows. This reduces the complexity significantly by avoiding the need to check all combinations.
⚙️
Algorithm
2 steps- 1Step 1: Check each row to see if it contains only zeros. If found, return that row's index.
- 2Step 2: If no single row is valid, check pairs of rows to see if their combined column sums meet the criteria.
solution.py11 lines
1def findGoodSubset(grid):
2 m = len(grid)
3 for i in range(m):
4 if all(x == 0 for x in grid[i]):
5 return [i]
6 for i in range(m):
7 for j in range(i + 1, m):
8 col_sums = [grid[i][k] + grid[j][k] for k in range(len(grid[0]))]
9 if all(col_sum <= 1 for col_sum in col_sums):
10 return [i, j]
11 return []ℹ
Complexity note: This complexity is O(n) because we only check each row once for zeros and then at most n pairs of rows, making it linear in terms of the number of rows.
- 1A good subset can be a single row of all zeros.
- 2If no single row exists, check pairs of rows.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.