oneby7

Binary Search Searching a matrix

256. Row with the Most 1s

Medium

You are given a grid matrix with m rows and n columns, in which every cell holds 0 or 1. Every row is sorted: its 0s, if it has any, come first, and its 1s come after them.

Return the index of the row that holds the most 1s. Rows are numbered from 0. If several rows hold the same largest number of 1s, return the smallest of their indexes. If no row holds a 1, return -1.

Example 1

0011011100010111

Input: matrix = [[0, 0, 1, 1], [0, 1, 1, 1], [0, 0, 0, 1], [0, 1, 1, 1]]

Output: 1

Explanation: Row 0 holds two 1s, rows 1 and 3 hold three each, and row 2 holds one. Rows 1 and 3 tie for the most, and the smaller index is 1.

Example 2

000000

Input: matrix = [[0, 0, 0], [0, 0, 0]]

Output: -1

Explanation: No row holds a 1.

Example 3

0011

Input: matrix = [[0], [0], [1], [1]]

Output: 2

Explanation: The grid is one column wide. Rows 2 and 3 hold one 1 each, and row 2 comes first.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[0, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 1, 1], [0, 1, 1, 1, 1]]

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • matrix[i][j] is 0 or 1.
  • In every row, all the 0s come before all the 1s.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.