Search in 2D matrix - II

Binary Search 2D Arrays Hard
  • This problem is at the heart of many search engines, like Google Maps or Yelp, where a ton of geospatial data exists with specific sorting around latitude (rows) and longitude (columns)
  • The restaurants, shops, or other points of interests are looked up efficiently, similar to searching for a target in a 2D matrix
  • Adopting a 2D array matrix search optimization like this can significantly speed up the search and improve the user interaction experience

Given a 2D array matrix where each row is sorted in ascending order from left to right and each column is sorted in ascending order from top to bottom, write an efficient algorithm to search for a specific integer target in the matrix.

Examples:

Input: matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], target = 5

Output: True

Explanation: The target 5 exists in the matrix in the index (1,1)

Input: matrix= [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], target = 20

Output: False

Explanation: The target 20 does not exist in the matrix.

Input: matrix= [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], target = 1

Constraints

  •   n == matrix.length
  •   m == matrix[i].length
  •   1 <= n, m <= 300
  •   -109 <= matrix[i][j] <= 109
  •   All the integers in each row are sorted in ascending order.
  •   All the integers in each column are sorted in ascending order.
  •   -109 <= target <= 109

Hints

  • Start at the top-right corner as it provides a vantage point: Moving left reduces the value. Moving down increases the value.
  • Perform binary search on each row to find the target. If the target may be present in multiple rows, narrow the search space by limiting to rows where row[0]≤target≤row[n−1].

Company Tags

Texas Instruments Shopify GE Healthcare Medtronic Nutanix Optum Freshworks Oracle HCL Technologies Unity Technologies Chewy Cerner Etsy Riot Games Deloitte Instacart Splunk Flipkart Rakuten Dropbox Philips Healthcare Bain & Company Zynga Target Red Hat Google Microsoft Amazon Meta Apple Netflix Adobe