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
Find Good Subset of MatrixINPUT MATRIX0110Row 0:Row 1:Binary matrix (0s and 1s)Need: column_sum ≤ floor(k/2)ALGORITHM STEPS1Try subset {0,1}2Calculate column sums3Col 0: 0+1=1, Col 1: 1+0=14Check: k=2, need ≤floor(2/2)=1✓ Both columns: 1 ≤ 1FINAL RESULTOutput:[0, 1]Row indices of good subsetBoth rows satisfy constraintKey Insight:A good subset has all column sums ≤ floor(subset_size/2). Try all subsetsor use greedy approach for faster practical solutions.TutorialsPoint - Find a Good Subset of the Matrix | Matrix Algorithm
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
12.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen