Find the row with maximum number of 1s?
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s.
Example Input matrix 0 1 1 1 0 0 1 1 1 1 1 1 // this row has maximum 1s 0 0 0 0 Output: 2
A simple method is to do a row wise traversal of the matrix, count the number of 1s in each row and compare the count with max. Finally, return the index of row with maximum 1s. The time complexity of this method is O(m*n) where m is number of rows and n is number of columns in matrix.
We can do better. Since each row is sorted, we can use Binary Search to count of 1s in each row. We find the index of first instance of 1 in each row. The count of 1s will be equal to total number of columns minus the index of first 1.
See the following code for implementation of the above approach.
Index of row with maximum 1s is 2
Time Complexity: O(mLogn) where m is a number of rows and n is a number of columns in a matrix.