Row with Maximum Ones in a Row-Wise Sorted Binary Matrix

viaGlassdoor

Problem: Given a binary matrix where each row is sorted (all 0s followed by all 1s), find the row with the maximum number of 1s, in O(n) time (not O(n*m)).

Constraints: Matrix is n x m, each row individually sorted in non-decreasing order.

Example: [[0,0,1,1],[0,1,1,1],[0,0,0,1]] -> row index 1 has the most 1s (3).

Approach: Start at the top-right corner of the matrix. If the current cell is 1, move left within the same row (recording this row as the current best) until a 0 is found or the row boundary is reached; if the current cell is 0, move down to the next row. Because each row is sorted, this traversal only takes at most O(n+m) steps total across the whole matrix.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account