Row With Maximum Ones solution and explanation
7 more videos on this problem
Row With Maximum Ones - Leetcode 2643 - PythonAlgorithms Casts · 4:36 · 784 views
Leetcode 2643. Row With Maximum Ones | Weekly Contest 341 | Leetcode weekly contest SolutionOffCampus Phodenge | Aman Chowdhury · 10:02 · 602 views
2643. Row With Maximum Ones (Leetcode Easy)Programming Live with Larry · 3:17 · 308 views
Leetcode Weekly contest 341 - Easy - Row With Maximum OnesPrakhar Agrawal · 2:58 · 166 views
Row With Maximum Ones | 6376 | LeetCode || c++ || Java || LeetCode weekly Contest solutionGrowup Code · 6:59 · 84 views
LeetCode: 2643. Row With Maximum Ones | Day 14CodeWithMaaz · 9:20 · 44 views
Row With Maximum Ones | LeetCode-2643 | Detailed Explanation | Brute Force + Optimal ApproachNayan Mandal · 11:31 · 17 views
Day 789: LeetCode Problem 2643. Row With Maximum Ones - SwiftiOSxBank · 7:38 · 6 views
The problem
Given a m x n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row.
In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.
Return an array containing the index of the row, and the number of ones in it.
Example 1:
Input: mat = [[0,1],[1,0]]
Output: [0,1]
Explanation: Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1). So, the answer is [0,1].
Example 2:
Input: mat = [[0,0,0],[0,1,1]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones(2). So we return its index,1, and the count. So, the answer is [1,2].
Example 3:
Input: mat = [[0,0],[1,1],[0,0]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones (2). So the answer is [1,2].
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 100mat[i][j]is either0or1.
Approach overview
Problem Overview: You are given a binary matrix where each cell contains either 0 or 1. The task is to return the index of the row that contains the maximum number of 1s and the count of those ones. If multiple rows contain the same maximum number, you return the smallest row index.
Approach 1: Brute Force Row Scan (Time: O(m*n), Space: O(1))
The most direct solution is to iterate through every row and count how many 1s it contains. For each row, loop through all columns and increment a counter whenever you encounter a 1. Keep track of the best result using two variables: maxOnes and rowIndex. Whenever the current row's count exceeds maxOnes, update both values.
This works because the matrix size is small enough that scanning every cell is completely acceptable. The algorithm simply performs a nested iteration: the outer loop walks through rows and the inner loop scans the elements of that row. The total time complexity becomes O(m*n), where m is the number of rows and n is the number of columns. Only a few integer variables are used, so the extra space complexity stays O(1). This approach relies only on basic traversal of a 2D array, making it easy to implement in any language.
Approach 2: Row Sum Using Built-in Aggregation (Time: O(m*n), Space: O(1))
A slightly cleaner variation uses built-in aggregation functions such as sum() in Python or manual accumulation utilities in other languages. Instead of incrementing a counter inside an inner loop, compute the number of ones in a row using a single expression like rowSum = sum(matrix[i]). Then compare that value with the current maximum and update the result if needed.
The algorithm still scans every element of the matrix internally, so the time complexity remains O(m*n). Space usage also stays O(1) since only a few tracking variables are maintained. The advantage is readability: the intent becomes clear immediately—calculate the number of ones in each row and keep the row with the largest total.
Recommended for interviews: Interviewers expect the straightforward row scanning solution. The brute force approach already runs in optimal time because every cell may need to be inspected in the worst case. Focus on writing clean traversal logic, correctly tracking the maximum count, and handling ties by keeping the smallest row index.
Approach 1: Brute Force Approach
This approach iterates through each row of the matrix, counts the number of ones in each row, and keeps track of the row with the maximum number of ones.
def row_with_max_ones(mat):
max_ones = -1
max_row = -1
for i, row in enumerate(mat):
count = row.count(1)
if count > max_ones:
max_ones = count
max_row = i
return [max_row, max_ones]
# Example Usage
mat = [[0,0],[1,1],[0,0]]
result = row_with_max_ones(mat)
print(result)import java.util.*;
class Solution {
public int[] rowWithMaxOnes(int[][] mat) {
int maxOnes = -1, maxRow = -1;
for (int i = 0; i < mat.length; i++) {
int count = 0;
for (int j = 0; j < mat[i].length; j++) {
if (mat[i][j] == 1) count++;
}
if (count > maxOnes) {
maxOnes = count;
maxRow = i;
}
}
return new int[]{maxRow, maxOnes};
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] mat = {{0,0},{1,1},{0,0}};
System.out.println(Arrays.toString(sol.rowWithMaxOnes(mat)));
}
}#include <iostream>
#include <vector>
using namespace std;
pair<int, int> rowWithMaxOnes(const vector<vector<int>>& mat) {
int maxOnes = -1, maxRow = -1;
for (int i = 0; i < mat.size(); i++) {
int count = 0;
for (int j = 0; j < mat[i].size(); j++) {
if (mat[i][j] == 1) count++;
}
if (count > maxOnes) {
maxOnes = count;
maxRow = i;
}
}
return {maxRow, maxOnes};
}
int main() {
vector<vector<int>> mat = {{0,0},{1,1},{0,0}};
auto result = rowWithMaxOnes(mat);
cout << "[" << result.first << "," << result.second << "]" << endl;
return 0;
}function rowWithMaxOnes(mat) {
let maxOnes = -1, maxRow = -1;
for (let i = 0; i < mat.length; i++) {
let count = 0;
for (let j = 0; j < mat[i].length; j++) {
if (mat[i][j] === 1) count++;
}
if (count > maxOnes) {
maxOnes = count;
maxRow = i;
}
}
return [maxRow, maxOnes];
}
// Example Usage
let mat = [[0,0],[1,1],[0,0]];
let result = rowWithMaxOnes(mat);
console.log(result);#include <stdio.h>
#include <limits.h>
void findRowWithMaxOnes(int mat[][100], int m, int n, int *result) {
int maxOnes = INT_MIN, maxRow = -1;
for (int i = 0; i < m; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) count++;
}
if (count > maxOnes) {
maxOnes = count;
maxRow = i;
}
}
result[0] = maxRow;
result[1] = maxOnes;
}
int main() {
int mat[3][100] = {{0,0}, {1,1}, {0,0}};
int result[2];
findRowWithMaxOnes(mat, 3, 2, result);
printf("[%d,%d]\n", result[0], result[1]);
return 0;
}using System;
class Solution {
public int[] RowWithMaxOnes(int[][] mat) {
int maxOnes = -1, maxRow = -1;
for (int i = 0; i < mat.Length; i++) {
int count = 0;
for (int j = 0; j < mat[i].Length; j++) {
if (mat[i][j] == 1) count++;
}
if (count > maxOnes) {
maxOnes = count;
maxRow = i;
}
}
return new int[]{maxRow, maxOnes};
}
static void Main(string[] args) {
Solution sol = new Solution();
int[][] mat = new int[][] {
new int[] {0,0},
new int[] {1,1},
new int[] {0,0}
};
int[] result = sol.RowWithMaxOnes(mat);
Console.WriteLine($"[{result[0]},{result[1]}]");
}
}The function row_with_max_ones uses Python's built-in list.count() to find the number of ones in each row. This is compared to the current maximum count to find the row with the maximum ones.
Time Complexity: O(m * n).
Space Complexity: O(1).
Approach 2: Simulation
We initialize an array ans = [0, 0] to store the index of the row with the most 1s and the count of 1s.
Then, we iterate through each row of the matrix:
- Compute the number of
1s in the current row, denoted ascnt(since the matrix contains only0s and1s, we can directly sum up the row). - If
ans[1] < cnt, updateans = [i, cnt].
After finishing the iteration, we return ans.
The time complexity is O(m times n), where m and n are the number of rows and columns in the matrix, respectively. The space complexity is O(1).
function rowAndMaximumOnes(mat: number[][]): number[] {
const ans: number[] = [0, 0];
for (let i = 0; i < mat.length; i++) {
const cnt = mat[i].reduce((sum, num) => sum + num, 0);
if (ans[1] < cnt) {
ans[0] = i;
ans[1] = cnt;
}
}
return ans;
}func rowAndMaximumOnes(mat [][]int) []int {
ans := []int{0, 0}
for i, row := range mat {
cnt := 0
for _, x := range row {
cnt += x
}
if ans[1] < cnt {
ans = []int{i, cnt}
}
}
return ans
}impl Solution {
pub fn row_and_maximum_ones(mat: Vec<Vec<i32>>) -> Vec<i32> {
let mut ans = vec![0, 0];
for (i, row) in mat.iter().enumerate() {
let cnt = row.iter().sum();
if ans[1] < cnt {
ans = vec![i as i32, cnt];
}
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Brute Force Approach | Time Complexity: O(m * n). |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Row Scan | O(m*n) | O(1) | General case for any binary matrix. Simple and interview-friendly. |
| Row Sum Using Built-in Aggregation | O(m*n) | O(1) | Cleaner implementation when language provides fast row sum utilities. |
Frequently asked questions
Is Row With Maximum Ones easy or hard?
Row With Maximum Ones is classified as an Easy problem. It mainly tests basic matrix traversal, counting logic, and maintaining a running maximum while handling ties by returning the smallest row index.
Row With Maximum Ones Python/Java solution
In Python, you can compute the count using sum(matrix[i]) while iterating through rows. In Java or C++, loop through each element in the row and increment a counter when encountering 1. Both implementations run in O(m*n) time and O(1) space.
How to solve Row With Maximum Ones in O(n)?
Pure O(n) time is not possible unless additional constraints exist because the algorithm may need to inspect every element in the matrix. The standard solution scans all rows and columns, resulting in O(m*n) time complexity while maintaining constant extra space.
What is the best approach for Row With Maximum Ones?
The best approach is scanning each row and counting the number of 1s. Track the maximum count and the row index while iterating through the matrix. This brute force traversal runs in O(m*n) time and O(1) extra space and is already optimal because every cell may need to be inspected.
Is Row With Maximum Ones asked at Google/Amazon/Meta?
Problems involving matrix traversal and counting patterns appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, similar questions test your ability to iterate through a 2D matrix and track aggregates efficiently.
What data structure is used in Row With Maximum Ones?
The primary data structure is a 2D array or matrix. The algorithm iterates through rows and columns while maintaining simple counters to track the maximum number of ones and the corresponding row index.
What is the time complexity of Row With Maximum Ones?
The time complexity is O(m*n), where m is the number of rows and n is the number of columns in the matrix. Each element may be visited once while counting the number of 1s in every row. The space complexity remains O(1) because only a few variables are used for tracking.
