The problem statement involves searching for a given integer (target) within an m x n integer matrix that adheres to two key properties:

  1. Each row within the matrix is sorted in non-decreasing order.
  2. The first integer of each row is greater than the last integer of the previous row.

The objective is to determine whether the target integer exists within the matrix and to return true if it does and false otherwise. The solution must achieve this in $O(log(m \times n))$ time complexity.

Solution:

To solve this problem within the required time complexity $O(log(m \times n))$, we can use a binary search approach. Since the matrix’s rows are sorted and the first integer of each row is greater than the last integer of the previous row, we can treat the matrix as a flattened sorted list and apply binary search on it.

Here is how to do it:

  1. Get the number of rows and columns in the matrix.
  2. Set the left pointer to 0 and the right to m x n - 1
  3. Perform binary search:
    1. Find the middle index between left and the right pointers.

    2. Calculate the corresponding rows and column in the matrix for the middle index:

      # Can either do this
      row, col = divmod(mid, n)
      print(matrix[row][col]) #print the middle value in the matrix
      
      # Or this
      mid_value = matrix[mid // n][mid % n]
      
    3. Compare the target with the element at the calculated row and column.

    4. If the target found, return true.

    5. If the target is less than the element, move the right pointer to the middle - 1 index.

    6. If the target is greater than the element, move the left pointer to the middle + 1 index.

  4. If target not found, return false.

Implementation:

def searchMatrix(matrix, target):
    if not matrix or not matrix[0]:
        return False
    
    m, n = len(matrix), len(matrix[0])
    left, right = 0, m * n - 1
    
    while left <= right:
        mid = (left + right) // 2
        mid_value = matrix[mid // n][mid % n]
        
        if target == mid_value:
            return True
        elif target < mid_value:
            right = mid - 1
        else:
            left = mid + 1
            
    return False

Another problem statement could be to search a given target value within m x n integer matrix. The matrix is structured such that all row’s integers are sorted in ascending order from left to right, and all column’s integers are sorted in ascending order from top to bottom. The goal is to determine whether the target value exists in the matrix, returning true if so, and false otherwise.

A good approach is to start from the top-right corner of the matrix. The algorithm proceeds as follows:

  1. Initialize the position at the top-right corner of the matrix, let’s call it (row, col)