Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/row-with-max-1s0023/1
Row with max 1s
Difficulty: Medium Accuracy: 33.09%
You are given a 2D binary array arr[][] consisting of only 1s and 0s. Each row of the array is sorted in non-decreasing order. Your task is to find and return the index of the first row that contains the maximum number of 1s. If no such row exists, return -1.
Note:
β’ The array follows 0-based indexing.
β’ The number of rows and columns in the array are denoted by n and m respectively.
Examples:
Input: arr[][] = [[0,1,1,1], [0,0,1,1], [1,1,1,1], [0,0,0,0]]
Output: 2
Explanation: Row 2 contains the most number of 1s (4 1s). Hence, the output is 2.
Input: arr[][] = [[0,0], [1,1]]
Output: 1
Explanation: Row 1 contains the most number of 1s (2 1s). Hence, the output is 1.
Input: arr[][] = [[0,0], [0,0]]
Output: -1
Explanation: No row contains any 1s, so the output is -1.
Constraints:
1 β€ arr.size(), arr[i].size() β€ 103
0 β€ arr[i][j] β€ 1
Solution:
class Solution:
def rowWithMax1s(self, arr):
n, m = len(arr), len(arr[0])
i, j = 0, m - 1
ans = -1
while i < n and j >= 0:
if arr[i][j] == 1:
ans = i
j -= 1
else:
i += 1
return ans
Top comments (0)