# Find index of the row containing maximum number of 1’s in a binary matrix

Given a binary M x N row-wise sorted matrix, find a row which contains maximum number of 1 in linear time.

For example,

Input:

[ 0 0 0 1 1 ]
[ 0 0 1 1 1 ]
[ 0 0 0 0 0 ]
[ 0 1 1 1 1 ]
[ 0 0 0 0 1 ]

Output: Maximum 1’s are present in the row 4

The idea is to start from the top-right corner of the matrix and do the following

– if current cell has value 1, continue moving left till we encounter 0 or all columns are processed, else
– if current cell has value 0, continue moving down till we encounter 1 or all rows are processed.

Finally, we return the row index of last cell in which we have seen 1.

C++ implementation –

Output:

Maximum 1’s are present in the row 4

The time complexity of above solution is O(M + N) and auxiliary space used by the program is O(1).

(2 votes, average: 5.00 out of 5)

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Subscribe
Notify of
Guest
arandomguy

what is the logic behind this? How does it work correctly?

Guest
arandomguy

ok got it. didn’t read the problem carefully “row wise sorted binary matrix”.

Guest

I dont think this is right..you only move down if you hit a 0 in the very last element in every row.. therefore you get 2. I tried the exact code and it didn’t work. Second of all, how is the complexity O(N+M) ? You are going through the matrix row-wise and column-wise. I think it’s O(N*M).

Guest

Code works fine. I think you’re confused somewhere. Please read the problem statement again and try to relate the logic. If you still think you’re right, kindly provide a test case where the code fails.
Also time complexity remains O(N+M) since we either go left or bottom, and not in other two directions at any point.

Guest

Sorry, just made the same mistake as arandomguy below. The solution is correct.