Maximum Rows Covered by Columns - Problem

You are given an m x n binary matrix matrix and an integer numSelect.

Your goal is to select exactly numSelect distinct columns from matrix such that you cover as many rows as possible.

A row is considered covered if all the 1's in that row are also part of a column that you have selected. If a row does not have any 1s, it is also considered covered.

More formally, let us consider selected = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row i is covered by selected if:

  • For each cell where matrix[i][j] == 1, the column j is in selected.
  • Or, no cell in row i has a value of 1.

Return the maximum number of rows that can be covered by a set of numSelect columns.

Input & Output

Example 1 — Basic Coverage
$ Input: matrix = [[0,0,0],[1,0,1]], numSelect = 2
Output: 2
💡 Note: Select columns [0,2]: Row 0 has no 1s (covered), Row 1 has 1s at positions 0,2 which are both selected (covered). Total: 2 rows.
Example 2 — Partial Coverage
$ Input: matrix = [[1],[0]], numSelect = 1
Output: 2
💡 Note: Select column [0]: Row 0 has 1 at position 0 (covered), Row 1 has no 1s (covered). Both rows covered.
Example 3 — Impossible Full Coverage
$ Input: matrix = [[1,0],[0,1]], numSelect = 1
Output: 1
💡 Note: Can only select 1 column. Either column covers exactly 1 row, so maximum is 1.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 12
  • matrix[i][j] is either 0 or 1
  • 1 ≤ numSelect ≤ n

Visualization

Tap to expand
Maximum Rows Covered by Columns INPUT Binary Matrix (2x3) C0 C1 C2 R0 0 0 0 R1 1 0 1 Input Values: matrix = [[0,0,0],[1,0,1]] numSelect = 2 Select 2 columns to cover rows = Cell with 1 (must cover) = Cell with 0 ALGORITHM STEPS 1 Generate Combinations All ways to pick 2 cols from 3 {C0,C1}, {C0,C2}, {C1,C2} C(3,2) = 3 combinations 2 Check Each Combination Count covered rows per combo 3 Evaluate Coverage Row covered if all 1s selected {C0,C1}: R0[OK] R1[X] = 1 {C0,C2}: R0[OK] R1[OK] = 2 {C1,C2}: R0[OK] R1[X] = 1 R0 has no 1s (always covered) 4 Return Maximum Best coverage = 2 rows FINAL RESULT Optimal Selection: {C0, C2} C0 C1 C2 R0 0 0 0 OK R1 1 0 1 OK Row 0: No 1s (auto-covered) Row 1: 1s at C0,C2 (both selected) Both rows are covered! Output: 2 Maximum rows covered = 2 Columns selected: C0, C2 Key Insight: Use bitmask enumeration to try all C(n, numSelect) column combinations efficiently. For each combination, check if selected columns cover all 1s in each row using bitwise AND. Time Complexity: O(2^n * m) where n=columns, m=rows. Optimal for small matrices. TutorialsPoint - Maximum Rows Covered by Columns | Optimal Solution (Bitmask)
Asked in
Google 12 Microsoft 8 Amazon 6 Meta 4
12.0K Views
Medium Frequency
~25 min Avg. Time
285 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