Row With Maximum Ones — LeetCode 2643 Python Solution

EasyArrayMatrix
Problem
#2643
Reading time
2 min

The problem

Given a m x n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row. In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.

Example

Input
mat = [[0,1],[1,0]]
Output
[0,1]
Explanation
Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1). So, the answer is [0,1].

Python solution

Python
class Solution:
    def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
        ans = [0, 0]
        for i, row in enumerate(mat):
            cnt = sum(row)
            if ans[1] < cnt:
                ans = [i, cnt]
        return ans

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns in the matrix, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2643. Row With Maximum Ones is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2643. Row With Maximum Ones?
LeetCode 2643. Row With Maximum Ones is rated Easy on LeetCode.
What is the time complexity of LeetCode 2643. Row With Maximum Ones?
The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns in the matrix, respectively.
What is the space complexity of LeetCode 2643. Row With Maximum Ones?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2643. Row With Maximum Ones cover?
LeetCode 2643. Row With Maximum Ones is tagged Array 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