Magicsheet logo

Maximum Number of Ones

Hard
97.6%
Updated 6/1/2025

Maximum Number of Ones

What is this problem about?

The Maximum Number of Ones coding problem presents a binary matrix (0s and 1s) and asks you to find the row with the maximum number of ones. It's often implied that the rows are sorted, or you need to consider how to efficiently find this in an unsorted or larger matrix.

Why is this asked in interviews?

Qualcomm asks this problem to test basic matrix traversal and optimization techniques. If the matrix is sorted (all 1s appear before 0s in each row), it becomes a classic application of a two-pointer approach or binary search. If unsorted, it's a direct traversal or potentially a more complex data structure problem if updates are involved.

Algorithmic pattern used

Two Pointers (for sorted rows): If each row is sorted (all 1s followed by 0s, or vice versa), a two-pointer approach is optimal. Start from the top-right corner. If the current element is a '1', it means all elements to its left in that row are also '1's. So, update the max_ones_row and move left (decrement column). If the current element is a '0', it means all elements below it in that column might have more ones, so move down (increment row). This approach takes O(rows + cols) time.

Brute-force (for unsorted rows): For an unsorted matrix, the simplest approach is to iterate through each row, count the ones, and keep track of the row with the maximum count. This takes O(rows * cols) time.

Example explanation

Sorted Matrix:

0 0 1 1
0 1 1 1
0 0 0 1
1 1 1 1
  • Start (0,3). Grid[0][3] = 1. max_ones_row = 0, max_ones_count = 1. Move left to (0,2).
  • Grid[0][2] = 1. max_ones_count becomes 2. Move left to (0,1).
  • Grid[0][1] = 0. Move down to (1,1).
  • Grid[1][1] = 1. max_ones_count could be 3 (from 1,1 to 1,3). max_ones_row = 1. Move left to (1,0).
  • Grid[1][0] = 0. Move down to (2,0).
  • Grid[2][0] = 0. Move down to (3,0).
  • Grid[3][0] = 1. max_ones_count could be 4 (from 3,0 to 3,3). max_ones_row = 3. Move left... until out of bounds.

The two-pointer approach would find row 3 with 4 ones.

Common mistakes candidates make

  • Not leveraging sorted property: If the rows are guaranteed to be sorted, a brute-force O(rows * cols) approach is sub-optimal. Always ask about matrix properties.
  • Off-by-one errors in counting: Ensure the count of ones is accurate for each row.
  • Handling empty or single-element rows/columns: Edge cases need to be considered.

Interview preparation tip

For the Math Sorting Heap (Priority Queue) Greedy interview pattern (though this problem primarily falls under Array/Matrix with Greedy/Two-Pointers), always consider special properties of the input. For matrices, questions often revolve around sortedness or specific traversal patterns. The two-pointer technique for sorted rows is a classic optimization that should be in your toolbox.

Similar Questions