Row Of A Matrix With Maximum Ones

You are given a 2D matrix (containing either ‘0’ or ‘1’) of size N x M, where each row is in sorted order. Find the 0-based index of the first row that has the maximum number of 1's.

For example :
For given 2D matrix:

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

The maximum number of 1’s are present in row 1 i.e. 3, considering the 0-based indexing so the result is 1.
Note :
If two rows have the same number of 1’s then return the row with a lower index.
Input Format :
 The first line of input contains an integer 'T' representing the number of the test case. Then the test cases are as follows.

 The first line of each test case contains two integers ‘N’ and ‘M’ representing the number of rows and number of columns of the 2D matrix.

 Each of the next N lines contains M space-separated integers representing the elements of the matrix ARR.
Output Format :
For each test case,print the row index which contains the maximum number of 1’s.
Note :
You do not need to print anything; It has already been taken care of. Just implement the given function.
Constraints :
1 ≤ T ≤ 50
1 ≤ N,M ≤ 100
0 ≤ ARR[i][j] ≤ 1

Where ARR[i][j] denotes the matrix elements.

Time Limit: 1 sec 
CodingNinjas
author
2y
Brute Force

Our intuition is to traverse the given matrix row by row, and keep on counting the number of ‘1’s in each row and compare the count with max. And finally, return the index of the row with t...read more

CodingNinjas
author
2y
Binary Search

In the previous approach, we were iterating through all the elements of the matrix. Do we really need to do that? Think of how we can search for a point where the 1’s starts to appear sin...read more

CodingNinjas
author
2y
Optimized Method

In the previous approach, we were searching in each of the given matrix. Can you think of a case in which we can really skip a row in order to make our approach more optimized?

Steps a...read more

Add answer anonymously...
Cisco Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter