Find a Good Subset of the Matrix - Problem
Matrix Row Selection Challenge
You're given a binary matrix and need to find a "good" subset of rows. But what makes a subset "good"?
A subset is considered good when each column's sum is at most half the number of selected rows. More formally, if you select
Goal: Return the indices of any good subset of rows in ascending order, or an empty array if no good subset exists.
Example: If you select 3 rows, each column can have at most 1 one (since ⌊3/2⌋ = 1).
You're given a binary matrix and need to find a "good" subset of rows. But what makes a subset "good"?
A subset is considered good when each column's sum is at most half the number of selected rows. More formally, if you select
k rows, then every column should have at most ⌊k/2⌋ ones.Goal: Return the indices of any good subset of rows in ascending order, or an empty array if no good subset exists.
Example: If you select 3 rows, each column can have at most 1 one (since ⌊3/2⌋ = 1).
Input & Output
example_1.py — Basic Case
$
Input:
grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]]
›
Output:
[0,1]
💡 Note:
Rows 0 and 1 form a good subset of size 2. Each column sum is at most ⌊2/2⌋ = 1: Column 0: 0+0=0, Column 1: 1+0=1, Column 2: 1+0=1, Column 3: 0+1=1.
example_2.py — All Zeros Row
$
Input:
grid = [[0,0,0],[1,0,1]]
›
Output:
[0]
💡 Note:
Row 0 is all zeros, forming a good subset of size 1. Each column sum is 0 ≤ ⌊1/2⌋ = 0.
example_3.py — No Good Subset
$
Input:
grid = [[1,1,1],[1,1,1]]
›
Output:
[]
💡 Note:
No good subset exists. Any single row has column sums > 0, and both rows together have column sums = 2 > ⌊2/2⌋ = 1.
Constraints
- m == grid.length
- n == grid[0].length
- 1 ≤ m, n ≤ 104
- 1 ≤ m × n ≤ 105
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Convert to Bitmasks
Each row becomes a binary number representing skill sets
2
Find Zero Row
A person with no skills forms a valid team of size 1
3
Find Complementary Pair
Two people with completely different skills form a balanced team
Key Takeaway
🎯 Key Insight: Mathematical properties allow us to solve this efficiently by only checking subsets of size 1 and 2, avoiding exponential complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code