Find a Good Subset of the Matrix - Problem
You are given a 0-indexed m x n binary matrix grid.
Let us call a non-empty subset of rows good if the sum of each column of the subset is at most half of the length of the subset.
More formally, if the length of the chosen subset of rows is k, then the sum of each column should be at most floor(k / 2).
Return an integer array that contains row indices of a good subset sorted in ascending order.
If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.
A subset of rows of the matrix grid is any matrix that can be obtained by deleting some (possibly none or all) rows from grid.
Input & Output
Example 1 — Basic 2x2 Matrix
$
Input:
grid = [[0,1],[1,0]]
›
Output:
[0,1]
💡 Note:
Both rows form a good subset: column sums are [1,1], subset size k=2, so floor(2/2)=1. Since 1≤1 for both columns, this is valid.
Example 2 — Single Row Valid
$
Input:
grid = [[1,1,1]]
›
Output:
[0]
💡 Note:
Single row subset: column sums are [1,1,1], k=1, so floor(1/2)=0. Since all columns have sum 1 > 0, we need a different subset or return empty.
Example 3 — No Valid Subset
$
Input:
grid = [[1,1],[1,1]]
›
Output:
[]
💡 Note:
Any non-empty subset will have column sums that exceed floor(k/2). For k=1: need ≤0, but get 1. For k=2: need ≤1, but get 2.
Constraints
- 1 ≤ m, n ≤ 12
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code