Search in a 2D matrix

Binary Search 2D Arrays Hard
  • This problem is essentially a form of sorted matrix search, a concept widely applied in database querying systems and search engines
  • When handling large volumes of data arranged in a sorted format (like timestamps/logs), efficient searching algorithms are critical for performance
  • Applications like Google, where millions of search queries are performed each second, need to effectively implement algorithms similar to this problem in their infrastructure
  • These systems frequently use multi-dimensional arrays (matrices) for quicker access and traversal, hence the significance of such problems

Given a 2-D array mat where the elements of each row are sorted in non-decreasing order, and the first element of a row is greater than the last element of the previous row (if it exists), and an integer target, determine if the target exists in the given mat or not.

Examples:

Input: mat = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ], target = 8

Output: True

Explanation: The target = 8 exists in the 'mat' at index (1, 3).

Input: mat = [ [1, 2, 4], [6, 7, 8], [9, 10, 34] ], target = 78

Output: False

Explanation: The target = 78 does not exist in the 'mat'. Therefore in the output, we see 'false'.

Input: mat = [ [1, 2, 4], [6, 7, 8], [9, 10, 34] ], target = 7

Constraints

  •   n == mat.length
  •   m == mat[i].length
  •   1 <= m, n <= 100
  •   -104 <= mat[i][j], target <= 104

Hints

  • Treat the matrix as a 1D array with indices ranging from 0 to m×n−1, where m is the number of rows and n is the number of columns.
  • Map the 1D index mid to a 2D position using: row=mid/n, col=mid%n

Company Tags

Pinterest Square Docker Airbnb Bloomberg Ernst & Young Robinhood Epic Games Mastercard IBM American Express McKinsey & Company Dropbox HCL Technologies Lyft Chewy Intel PayPal Medtronic Seagate Technology Ubisoft Freshworks ARM Flipkart Siemens Healthineers Google Microsoft Amazon Meta Apple Netflix Adobe