#2643
Row With Maximum Ones
EasyArrayMatrixTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(m + n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(m + n)Space O(1)
The optimal solution leverages the fact that the matrix is binary. By using a two-pointer technique, we can efficiently find the row with the maximum ones without counting each row from scratch.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one at the start of the first row and the other at the end of the last column.
- 2Step 2: Traverse the matrix using the two pointers. If the current cell is 1, move the row pointer down and update the count of ones.
- 3Step 3: If the current cell is 0, move the column pointer left to check for more ones.
- 4Step 4: Keep track of the maximum count of ones and the corresponding row index.
- 5Step 5: Return the row index and the maximum count of ones.
solution.py15 lines
1def rowWithMaximumOnes(mat):
2 max_count = 0
3 row_index = 0
4 n = len(mat[0])
5 row, col = 0, n - 1
6 while row < len(mat) and col >= 0:
7 if mat[row][col] == 1:
8 count = n - col
9 if count > max_count:
10 max_count = count
11 row_index = row
12 row += 1
13 else:
14 col -= 1
15 return [row_index, max_count]ℹ
Complexity note: We traverse the matrix using two pointers, which allows us to skip unnecessary checks, leading to a time complexity of O(m + n). Space complexity remains O(1) as we only use a few variables.
- 1Using a two-pointer technique can significantly reduce the number of checks needed.
- 2Understanding the structure of the matrix (binary) allows for optimizations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.