Find row with maximum 1's

Binary Search 2D Arrays Hard
  • One real-world application of this problem can be found in Image Processing
  • Notably, in the case of binary images, which consists solely of 1s (indicating white pixels) and 0s (indicating black pixels)
  • By finding the row with the most white pixels (1s), certain characteristics of the image can be determined, such as the location of an object within the image
  • This concept is at the heart of many computer vision tasks that form the basis for features like facial recognition in apps like Facebook and Snapchat

Given a non-empty grid mat consisting of only 0s and 1s, where all the rows are sorted in ascending order, find the index of the row with the maximum number of ones.

Examples:

Input : mat = [ [1, 1, 1], [0, 0, 1], [0, 0, 0] ]

Output: 0

Explanation: The row with the maximum number of ones is 0 (0 - indexed).

Input: mat = [ [0, 0], [0, 0] ]

Output: -1

Explanation: The matrix does not contain any 1. So, -1 is the answer.

Input : mat = [ [0, 0, 1], [0, 1, 1], [0, 1, 1] ]

Constraints

  •   n == mat.length 
  •   m == mat[i].length 
  •   1 <= n, m <= 100 
  •   mat[i][j] is either 0 or 1.

Hints

  • "Since rows are sorted, the first 1 in a row determines the count of 1s. If a row contains n columns and the first 1 appears at index j, then the count of 1s in that row is n−j."
  • For each row, use binary search to find the index of the first 1. Keep track of the row with the maximum number of 1s as you iterate through the grid.

Company Tags

Alibaba JPMorgan Chase PwC Ernst & Young Roblox Zoho Philips Healthcare Salesforce Robinhood Uber GE Healthcare Visa ARM Cloudflare Wayfair Square Riot Games Epic Games DoorDash Optum Intel Epic Systems McKinsey & Company Docker Bloomberg Google Microsoft Amazon Meta Apple Netflix Adobe