Input: grid =[[0,1,1,0],[0,0,0,1],[1,1,1,1]]Output: [0,1]Explanation: We can choose the 0th and 1st rows to create a good subset of rows.The length of the chosen subset is2.- The sum of the 0th column is0+0=0, which is at most half of the length of the subset.- The sum of the 1st column is1+0=1, which is at most half of the length of the subset.- The sum of the 2nd column is1+0=1, which is at most half of the length of the subset.- The sum of the 3rd column is0+1=1, which is at most half of the length of the subset.
Input: grid =[[0]]Output: [0]Explanation: We can choose the 0th row to create a good subset of rows.The length of the chosen subset is1.- The sum of the 0th column is0, which is at most half of the length of the subset.
Each row in the matrix can be represented as a bitmask. The problem asks for a non-empty subset of rows such that, for each column, the sum of 1s is at most half the subset size. For binary matrices, this is only possible if no column has more than half 1s, which is only possible if the subset contains at most one 1 per column. Thus, we can look for either a single row of all 0s, or a pair of rows with no overlapping 1s (i.e., their bitmasks have no common set bits).
classSolution {
public List<Integer>goodSubsetofBinaryMatrix(int[][] grid) {
int m = grid.length, n = grid[0].length;
Map<Integer, Integer> mask2idx =new HashMap<>();
for (int i = 0; i < m; i++) {
int mask = 0;
for (int j = 0; j < n; j++) mask |= (grid[i][j]<< j);
if (mask == 0) return List.of(i);
mask2idx.putIfAbsent(mask, i);
}
for (var e1 : mask2idx.entrySet()) {
for (var e2 : mask2idx.entrySet()) {
if (e1.getValue() < e2.getValue() && (e1.getKey() & e2.getKey()) == 0)
return List.of(e1.getValue(), e2.getValue());
}
}
return List.of();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
fungoodSubsetofBinaryMatrix(grid: Array<IntArray>): List<Int> {
val m = grid.size
val n = grid[0].size
val mask2idx = mutableMapOf<Int, Int>()
for (i in0 until m) {
var mask = 0for (j in0 until n) mask = mask or (grid[i][j] shl j)
if (mask ==0) return listOf(i)
mask2idx.putIfAbsent(mask, i)
}
for ((mask1, i) in mask2idx) {
for ((mask2, j) in mask2idx) {
if (i < j && (mask1 and mask2) ==0) return listOf(i, j)
}
}
return emptyList()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defgoodSubsetofBinaryMatrix(self, grid: list[list[int]]) -> list[int]:
m, n = len(grid), len(grid[0])
mask2idx = {}
for i in range(m):
mask =0for j in range(n):
mask |= grid[i][j] << j
if mask ==0:
return [i]
if mask notin mask2idx:
mask2idx[mask] = i
for mask1, i in mask2idx.items():
for mask2, j in mask2idx.items():
if i < j and (mask1 & mask2) ==0:
return [i, j]
return []