Facebook Pixel

2643. Row With Maximum Ones

Problem Description

You are given a m x n binary matrix mat (containing only 0s and 1s). Your task is to find which row contains the maximum number of 1s.

The problem asks you to:

  1. Find the row that has the most 1s in it
  2. Count how many 1s are in that row
  3. If multiple rows have the same maximum count of 1s, choose the row with the smallest index (the one that appears first)

Return an array with two elements:

  • The first element is the 0-indexed position of the row with the most 1s
  • The second element is the count of 1s in that row

For example, if row 2 (0-indexed) has the maximum number of 1s, say 5 ones, you would return [2, 5].

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Since we need to find the row with the maximum number of 1s, the most straightforward approach is to examine each row one by one and keep track of which row has the most 1s so far.

The key insight is that we only need to maintain two pieces of information as we scan through the matrix:

  • The index of the current best row (the row with the most 1s we've seen so far)
  • The count of 1s in that best row

As we iterate through each row, we can count the 1s in the current row. Since the matrix is binary (only contains 0s and 1s), counting 1s is as simple as summing all elements in the row using sum(row).

We then compare this count with our current maximum. If the current row has more 1s than our previous best, we update our answer. If it has the same number or fewer 1s, we don't update - this naturally handles the requirement that when there's a tie, we should select the row with the smaller index (since we're processing rows in order from index 0 onwards).

This gives us a single-pass solution with O(m × n) time complexity, where we visit each element exactly once, and O(1) extra space since we only store the result array.

Solution Approach

We implement a simulation approach that iterates through the matrix once to find the desired row.

Step 1: Initialize the Result We start by initializing an array ans = [0, 0] where:

  • ans[0] stores the index of the row with the maximum 1s
  • ans[1] stores the count of 1s in that row

Initially, we assume row 0 has the maximum with 0 ones (this will be updated as we scan the matrix).

Step 2: Iterate Through Each Row We use enumerate(mat) to iterate through the matrix, which gives us both the row index i and the row content row.

Step 3: Count 1s in Current Row For each row, we calculate the count of 1s using cnt = sum(row). This works because:

  • The matrix is binary (only contains 0s and 1s)
  • Summing the row gives us the total number of 1s (since 0s don't contribute to the sum)

Step 4: Update Maximum if Necessary We compare the current row's count with our stored maximum:

  • If ans[1] < cnt (current row has more 1s than our previous best), we update ans = [i, cnt]
  • If ans[1] >= cnt, we don't update, which ensures that in case of a tie, we keep the row with the smaller index

Step 5: Return Result After processing all rows, ans contains the index of the row with the most 1s and the count of 1s in that row.

The algorithm makes a single pass through the matrix, examining each element exactly once, resulting in O(m × n) time complexity where m is the number of rows and n is the number of columns. The space complexity is O(1) as we only use a fixed amount of extra space for the result array.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with a small example matrix:

mat = [[0, 1],
       [1, 0],
       [1, 1]]

Initial State:

  • ans = [0, 0] (assuming row 0 has maximum with 0 ones initially)

Iteration 1 - Row 0: [0, 1]

  • Calculate count: cnt = sum([0, 1]) = 1
  • Compare: Is ans[1] < cnt? Is 0 < 1? Yes!
  • Update: ans = [0, 1] (row 0 has 1 one)

Iteration 2 - Row 1: [1, 0]

  • Calculate count: cnt = sum([1, 0]) = 1
  • Compare: Is ans[1] < cnt? Is 1 < 1? No!
  • No update: ans remains [0, 1] (tie goes to earlier row)

Iteration 3 - Row 2: [1, 1]

  • Calculate count: cnt = sum([1, 1]) = 2
  • Compare: Is ans[1] < cnt? Is 1 < 2? Yes!
  • Update: ans = [2, 2] (row 2 has 2 ones)

Final Result: [2, 2]

Row 2 (0-indexed) contains the maximum number of 1s (which is 2), so we return [2, 2].

This demonstrates how the algorithm:

  1. Tracks the best row seen so far
  2. Only updates when a strictly better row is found
  3. Naturally handles ties by keeping the first occurrence

Solution Implementation

1class Solution:
2    def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
3        # Initialize result array with [row_index, max_count]
4        # Default to row 0 with count 0
5        result = [0, 0]
6      
7        # Iterate through each row with its index
8        for row_index, row in enumerate(mat):
9            # Count the number of 1s in the current row
10            ones_count = sum(row)
11          
12            # Update result if current row has more 1s than previous maximum
13            if result[1] < ones_count:
14                result = [row_index, ones_count]
15      
16        # Return the row index with maximum 1s and the count
17        return result
18
1class Solution {
2    /**
3     * Finds the row with the maximum number of ones in a binary matrix.
4     * Returns an array containing the row index and the count of ones in that row.
5     * If multiple rows have the same maximum count, returns the row with the smallest index.
6     * 
7     * @param mat The input binary matrix (contains only 0s and 1s)
8     * @return An array where index 0 is the row index with maximum ones, 
9     *         and index 1 is the count of ones in that row
10     */
11    public int[] rowAndMaximumOnes(int[][] mat) {
12        // Initialize result array: [rowIndex, maxOnesCount]
13        int[] result = new int[2];
14      
15        // Iterate through each row of the matrix
16        for (int rowIndex = 0; rowIndex < mat.length; rowIndex++) {
17            // Count the number of ones in the current row
18            int onesCount = 0;
19            for (int element : mat[rowIndex]) {
20                onesCount += element;  // Since matrix is binary, adding element counts ones
21            }
22          
23            // Update result if current row has more ones than previous maximum
24            if (result[1] < onesCount) {
25                result[0] = rowIndex;     // Store the row index
26                result[1] = onesCount;    // Store the count of ones
27            }
28        }
29      
30        return result;
31    }
32}
33
1class Solution {
2public:
3    vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) {
4        // Initialize result vector to store [row_index, max_count]
5        // Default values are [0, 0]
6        vector<int> result(2);
7      
8        // Iterate through each row of the matrix
9        for (int rowIndex = 0; rowIndex < mat.size(); ++rowIndex) {
10            // Count the number of ones in the current row
11            // accumulate sums all elements in the row (since matrix contains only 0s and 1s)
12            int onesCount = accumulate(mat[rowIndex].begin(), mat[rowIndex].end(), 0);
13          
14            // Update result if current row has more ones than the previous maximum
15            if (result[1] < onesCount) {
16                result = {rowIndex, onesCount};
17            }
18        }
19      
20        // Return the row index with maximum ones and the count
21        return result;
22    }
23};
24
1/**
2 * Finds the row with the maximum number of ones in a binary matrix
3 * @param mat - A 2D binary matrix containing only 0s and 1s
4 * @returns An array where [0] is the row index with most ones, [1] is the count of ones
5 */
6function rowAndMaximumOnes(mat: number[][]): number[] {
7    // Initialize result array: [rowIndex, maxOnesCount]
8    const result: number[] = [0, 0];
9  
10    // Iterate through each row of the matrix
11    for (let rowIndex = 0; rowIndex < mat.length; rowIndex++) {
12        // Count the number of ones in the current row
13        const onesCount: number = mat[rowIndex].reduce((sum, value) => sum + value, 0);
14      
15        // Update result if current row has more ones than previous maximum
16        if (result[1] < onesCount) {
17            result[0] = rowIndex;
18            result[1] = onesCount;
19        }
20    }
21  
22    return result;
23}
24

Time and Space Complexity

Time Complexity: O(m × n)

The algorithm iterates through each row of the matrix using enumerate(mat), which takes O(m) time where m is the number of rows. For each row, it calculates the sum of all elements using sum(row), which takes O(n) time where n is the number of columns in each row. Since we perform the sum operation for each of the m rows, the total time complexity is O(m × n).

Space Complexity: O(1)

The algorithm uses only a constant amount of extra space. The ans variable is a list of fixed size 2, and the loop variables i, row, and cnt use constant space regardless of the input size. No additional data structures that scale with the input size are created, making the space complexity constant.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Incorrect Tie-Breaking Logic

A common mistake is using <= instead of < in the comparison condition, which would incorrectly update the result when counts are equal:

Incorrect Implementation:

for row_index, row in enumerate(mat):
    ones_count = sum(row)
    # Wrong: This updates even when counts are equal
    if result[1] <= ones_count:  
        result = [row_index, ones_count]

This would return the last row with the maximum count instead of the first one.

Correct Implementation:

for row_index, row in enumerate(mat):
    ones_count = sum(row)
    # Correct: Only update when strictly greater
    if result[1] < ones_count:
        result = [row_index, ones_count]

Pitfall 2: Not Handling Empty Matrix

While the problem typically guarantees at least one row, defensive programming suggests checking for edge cases:

Potential Issue:

def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
    result = [0, 0]  # Assumes row 0 exists
    for row_index, row in enumerate(mat):
        # ...

Safer Implementation:

def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
    if not mat or not mat[0]:
        return [0, 0]  # Handle empty matrix case
  
    result = [0, 0]
    for row_index, row in enumerate(mat):
        ones_count = sum(row)
        if result[1] < ones_count:
            result = [row_index, ones_count]
    return result

Pitfall 3: Manual Counting Instead of Using Built-in Functions

Some developers might unnecessarily complicate the counting logic:

Inefficient Approach:

ones_count = 0
for element in row:
    if element == 1:
        ones_count += 1

Better Approach:

ones_count = sum(row)  # Cleaner and more Pythonic

The built-in sum() function is not only more concise but also typically faster due to C-level optimization in Python's implementation.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which type of traversal does breadth first search do?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More