Row With Maximum Ones - Problem
You are analyzing a binary matrix where each cell contains either 0 or 1. Your task is to identify which row contains the maximum number of ones and return both the row index and the count of ones in that row.

Given an m ร— n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones. If multiple rows tie for the maximum count, choose the row with the smallest index.

Goal: Return an array [rowIndex, onesCount] where rowIndex is the index of the row with maximum ones, and onesCount is the number of ones in that row.

Example: In matrix [[0,1],[1,0]], both rows have 1 one, so we return [0, 1] (row 0 wins the tie).

Input & Output

example_1.py โ€” Basic Matrix
$ Input: mat = [[0,1],[1,0]]
โ€บ Output: [0,1]
๐Ÿ’ก Note: Both rows have exactly 1 one. Since row 0 comes first (smaller index), we return [0,1].
example_2.py โ€” Clear Winner
$ Input: mat = [[0,0,0],[0,1,1]]
โ€บ Output: [1,2]
๐Ÿ’ก Note: Row 0 has 0 ones, Row 1 has 2 ones. Row 1 has the maximum, so we return [1,2].
example_3.py โ€” All Zeros
$ Input: mat = [[0,0],[0,0]]
โ€บ Output: [0,0]
๐Ÿ’ก Note: All rows have 0 ones. Row 0 wins the tie (smallest index), so we return [0,0].

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 โ‰ค m, n โ‰ค 100
  • mat[i][j] is either 0 or 1
  • Matrix contains only binary values (0 or 1)

Visualization

Tap to expand
๐ŸŸ๏ธ Stadium Seating AnalysisSection 0:๐Ÿ‘ค๐Ÿ‘คCount: 2 people โœ“Section 1:๐Ÿ‘คCount: 1 personSection 2:๐Ÿ‘ค๐Ÿ‘คCount: 2 people๐Ÿ“Š Analysis ResultsSections 0 and 2 both have 2 people (maximum)๐Ÿ† Winner: Section 0 (lower section number wins ties)Result: [0, 2]
Understanding the Visualization
1
Survey Each Section
Walk through each row (section) and count occupied seats (1s)
2
Track the Winner
Keep track of which section has the most people so far
3
Handle Ties
If sections tie, choose the one with the lower number (earlier in the stadium)
4
Report Results
Return both the section number and how many people are in it
Key Takeaway
๐ŸŽฏ Key Insight: We must examine every row to find the maximum, but we can efficiently track the best result in a single pass through the matrix.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.0K Views
Medium Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen