Lecture 3 (Binary Search on 2D Arrays)¶
Find the row with maximum number of 1's¶
You have been given a non-empty grid ‘mat’ with 'n' rows and 'm' columns consisting of only 0s and 1s. All the rows are sorted in ascending order. Your task is to find the index of the row with the maximum number of ones. Note: If two rows have the same number of ones, consider the one with a smaller index. If there's no row with at least 1 zero, return -1.
Input Format: n = 3, m = 3,
mat[] =
1 1 1
0 0 1
0 0 0
Result: 0
Explanation: The row with the maximum number of ones is 0 (0 - indexed).
Input Format: n = 2, m = 2 ,
mat[] =
0 0
0 0
Result: -1
Explanation: The matrix does not contain any 1. So, -1 is the answer.
Approach 1 (Brute Force)¶
- Linear search on 2d arrays
In [ ]:
def row_max_1(grid):
R ,C = len(grid) , len(grid[0])
max_count,result = 0,-1
for r in range(R):
count = 0
for c in range(C):
if grid[r][c] == 1:
count +=1
if count > max_count:
max_count = count
result = r
return [result,max_count]
print(row_max_1([[1,1,1],[0,0,1],[0,0,0]]))
print(row_max_1([[0,0],[0,0]]))
[0, 3] [-1, 0] [0, 1]
Complexity¶
O(R x C) : R = len(grid) and C = len(grid[0])
O(1)
Approach 2 (Binary search)¶
In [ ]:
def row_max_1(grid):
R ,C = len(grid) , len(grid[0])
max_count,result = 0,-1
for r in range(R):
left , right = 0,C-1
first_one = C
while left <= right:
mid = (left + right)//2
if grid[r][mid] ==1:
first_one = mid
right = mid-1
else:
left = mid +1
count = C - first_one
if count > max_count:
max_count = count
result = r
return [result,max_count]
print(row_max_1([[1,1,1],[0,0,1],[0,0,0]]))
print(row_max_1([[0,0],[0,0]]))
[0, 3] [-1, 0] [1, 2]
Complexity¶
O(R x log C) : R = len(grid) and C = len(grid[0])
O(1)