![]() |
VOOZH | about |
Given a binary matrix (containing only 0 and 1) of order n×n. All rows are sorted already, We need to find the row number with the maximum number of 1s. Also, find the number 1 in that row.
Note: in case of a tie, print the smaller row number.
Examples :
Input : mat[3][3] = {0, 0, 1,
0, 1, 1,
0, 0, 0}
Output : Row number = 2, MaxCount = 2
Input : mat[3][3] = {1, 1, 1,
1, 1, 1,
0, 0, 0}
Output : Row number = 1, MaxCount = 3
Basic Approach: Traverse whole of the matrix and for each row find the number of 1 and among all that keep updating the row number with the maximum number of 1. This approach will result in O(n^2) time complexity.
Row number = 4, MaxCount = 3
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Better Approach: We can perform better if we try to apply the binary search for finding the position of the first 1 in each row and as per that we can find the number of 1 from each row as each row is in sorted order. This will result in O(n log (n)) time complexity.
Efficient Approach: Start with the top right corner with index (1, n) and try to go left until you reach the last 1 in that row (jth column), now if we traverse left to that row, we will find 0, so switch to the row just below, with the same column. Now your position will be (2, j) again in the 2nd row if the jth element is 1 try to go left until you find the last 1 otherwise in the 2nd row if jth element is 0 goes to the next row. So Finally say if you are at any ith row and jth column which is the index of last 1 from right in that row, increment i. So now if we have Aij = 0 again increment i otherwise keep decreasing j until you find the last 1 in that particular row.
Sample Illustration :
Algorithm :
for (int i=0, j=n-1; i<n;i++)
{
// find left most position of 1 in a row
// find 1st zero in a row
while (arr[i][j]==1)
{
row = i;
j--;
}
}
cout << "Row number =" << row+1;
cout << "MaxCount =" << n-j;
Implementation:
Row number = 4, MaxCount = 3
Time Complexity: O(N), where N is the number of rows and columns in the given matrix.
Auxiliary Space: O(1)
the idea is to use the lower bound function to find the recent occurrence of 1 in the present row just to track the length of 1.
Steps to solve this problem:
1. Initialize a vector ans of size 2 with all elements set to 0.
2. Initialize two integer variables sum and temp to 0.
3. Iterate over each row of the mat matrix as i from 0 to N-1.
*initialize a and store the lower bound of 1 in it.
*Set temp to the current value of sum.
*Update sum variable to the maximum value between sum and N-a.
*If the value of sum has changed and is greater than the previous value of temp, update the values of ans with the current row index i and N-a.
4. Return the updated vector ans.
Implementation:
Row number = 4, MaxCount = 3
Time Complexity: O(NLogN), where N is the number of rows and columns in the given matrix.
Auxiliary Space: O(1)
This approach is contributed by Prateek Kumar Singh (pkrsingh025)