Maximum Rows Covered by Columns — LeetCode 2397 Python Solution

MediumBit ManipulationArrayBacktrackingEnumerationMatrix
Problem
#2397
Reading time
2 min

The 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.

Python solution

Python
class Solution:
    def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int:
        rows = []
        for row in matrix:
            mask = reduce(or_, (1 << j for j, x in enumerate(row) if x), 0)
            rows.append(mask)

        ans = 0
        for mask in range(1 << len(matrix[0])):
            if mask.bit_count() != numSelect:
                continue
            t = sum((x & mask) == x for x in rows)
            ans = max(ans, t)
        return ans

Complexity

MeasureComplexity
TimeO(2^n \times m)
SpaceO(m) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2397. Maximum Rows Covered by Columns is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2397. Maximum Rows Covered by Columns?
LeetCode 2397. Maximum Rows Covered by Columns is rated Medium on LeetCode.
What is the time complexity of LeetCode 2397. Maximum Rows Covered by Columns?
The Python solution on this page runs in O(2^n \times m).
What is the space complexity of LeetCode 2397. Maximum Rows Covered by Columns?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 2397. Maximum Rows Covered by Columns cover?
LeetCode 2397. Maximum Rows Covered by Columns is tagged Bit Manipulation, Array, Backtracking, Enumeration and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview