Find row with maximum number of 1s in sorted matrix

Problem: You are given a MxN matrix with each row sorted. Matrix is having only 0′s and 1′s. You have to find row wotth maximum number of 1′s. eg. matrix given: 000111 001111 011111 000011 111111 // row with max number of 1′s

Method 1: Brute force approach Traverse the matrix row wise and count number of 1′s. If the number of 1′s is greater than max count than store index of row. Return index with max 1′s. Time Complexity: O(MxN) M is no of rows,N is no of cols.

Method 2: Usng binary search(each row is sorted) We will find occurence of first 1. Total number o 1′s will be total coumns – index of first 1. Implementation of above approach:

Start from top right corner. If you encounter 0 go down. If you encounter 1 go right.

You will end up at the column from which maximum number of 1′s starts.

Example :

000111 001111 011111 000011 111111

start from (0,5) there is 1 so you go right (0,4) (current_answer = M-4-1 = 1 ) there is 1 so you go right (0,3) (current_answer = M-3-1 = 2 ) there is 1 so you go right (0,2) (current_answer = M-2-1 = 3 ) there is 0 so you go down (1,2) (current_answer = M-2-1 = 3 ) there is 1 so you go right (1,2) (current_answer = M-2-1 = 3 ) there is 1 so you go right (1,1) (current_answer = M-1-1 = 4 ) there is 0 so you go down (2,1) (current_answer = M-1-1 = 4 ) there is 1 so you go right (2,0) (current_answer = M-0-1 = 5 ) there is 0 so you go down(3,0) (current_answer = M-0-1 = 5 ) there is 0 so you go down (4,0) (current_answer = M-0-1 = 5 ) there is 1 so you … opps.. we found a row which has all 1′s. and that’s the answer. (current_answer = M-(-1)-1 = 6 )