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 –
 

Download   Run Code

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).

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
arandomguy
Guest

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

arandomguy
Guest

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

Aron
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).

Aditya
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.

Nikolay
Guest

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