{x}
blog image

Search a 2D Matrix II

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

 

Example 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 = 5
Output: true

Example 2:

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

 

Constraints:

  • m == matrix.length
  • n == 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

Solution Explanation for Search a 2D Matrix II

This problem asks to efficiently search for a target value within an m x n matrix where each row and column is sorted in ascending order. Two efficient approaches are presented: Binary Search and a linear search starting from a corner.

Solution 1: Binary Search (Row-wise)

This approach iterates through each row of the matrix and performs a binary search on that row to check if the target exists.

Algorithm:

  1. Iterate through rows: The outer loop iterates through each row of the matrix.
  2. Binary Search: For each row, a binary search (bisect_left in Python, Arrays.binarySearch in Java, lower_bound in C++, sort.SearchInts in Go, _.sortedIndex in TypeScript/JavaScript) is performed to find the index of the first element greater than or equal to the target. If the target is found, the function immediately returns true.
  3. Target not found: If the binary search completes for all rows without finding the target, the function returns false.

Time Complexity: O(m * log n), where 'm' is the number of rows and 'n' is the number of columns. This is because we perform a binary search (O(log n)) on each of the 'm' rows.

Space Complexity: O(1). The algorithm uses constant extra space.

Solution 2: Search from Bottom-Left (or Top-Right)

This approach uses a more optimized linear search strategy. It starts from either the bottom-left or top-right corner of the matrix and strategically moves based on comparisons with the target.

Algorithm (using Bottom-Left):

  1. Initialization: Start at the bottom-left corner of the matrix (i = m - 1, j = 0).
  2. Comparison: Compare the current element matrix[i][j] with the target:
    • If matrix[i][j] == target, return true.
    • If matrix[i][j] > target, move upwards (decrement i) because all elements to the right in the current row are larger.
    • If matrix[i][j] < target, move rightwards (increment j) because all elements above in the current column are smaller.
  3. Target not found: If the search reaches the top or right boundary without finding the target, return false.

Time Complexity: O(m + n). In the worst case, the algorithm traverses at most all the rows and columns once.

Space Complexity: O(1). Constant extra space is used.

Code Examples (Python):

Solution 1 (Binary Search):

import bisect
 
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
            j = bisect.bisect_left(row, target)
            if j < len(matrix[0]) and row[j] == target:
                return True
        return False

Solution 2 (Bottom-Left Search):

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        i, j = m - 1, 0
        while i >= 0 and j < n:
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:
                i -= 1
            else:
                j += 1
        return False

The code examples in other languages follow similar logic, adapting the specific binary search and array/matrix access methods for their respective languages. Solution 2 is generally preferred due to its superior time complexity in most cases.