Find the Earliest Row with the Most Ones

Quick Overview

Return the smallest-index row with the most ones and its one count, without assuming rows are sorted.

Find the Earliest Row with the Most Ones

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Given a nonempty binary matrix mat, return [rowIndex, oneCount] for a row containing the most ones. Break ties by choosing the smallest row index. Rows need not be sorted. ```cpp class Solution { public: vector<int> rowAndMaximumOnes(vector<vector<int>>& mat); }; ``` ### Examples **Example 1:** ```text Input: mat = [[1,0,1],[1,1,0],[0,0,0]] Output: [0,2] Explanation: Rows 0 and 1 each contain two ones, so the smaller index wins. ``` **Example 2:** ```text Input: mat = [[0],[0],[1]] Output: [2,1] Explanation: Only the third row contains a one. ``` ### Constraints - `m == mat.length`; `n == mat[i].length`. - `1 <= m, n <= 100`. - Each entry is 0 or 1. ### Clarifying Questions - Are row indices zero-based? Yes. - How are count ties resolved? Choose the smallest row index. - Must rows already be sorted? No. - What is the output order? Row index first, number of ones second. ```hint Check the boundary Check a matrix containing only zeroes. ```

Overview: Return the smallest-index row with the most ones and its one count, without assuming rows are sorted.

Amazon logo
Amazon
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Given a nonempty binary matrix mat, return [rowIndex, oneCount] for a row containing the most ones. Break ties by choosing the smallest row index. Rows need not be sorted.

class Solution {
public:
    vector<int> rowAndMaximumOnes(vector<vector<int>>& mat);
};

Examples

Example 1:

Input: mat = [[1,0,1],[1,1,0],[0,0,0]]
Output: [0,2]
Explanation: Rows 0 and 1 each contain two ones, so the smaller index wins.

Example 2:

Input: mat = [[0],[0],[1]]
Output: [2,1]
Explanation: Only the third row contains a one.

Constraints

  • m == mat.length ; n == mat[i].length .
  • 1 <= m, n <= 100 .
  • Each entry is 0 or 1.

Clarifying Questions Guidance

  • Are row indices zero-based? Yes.
  • How are count ties resolved? Choose the smallest row index.
  • Must rows already be sorted? No.
  • What is the output order? Row index first, number of ones second.