Search A 2D Matrix

To solve this coding challenge, we need to efficiently search for a target value in a 2D matrix that has distinct, sorted rows and columns. Since rows are sorted in non-decreasing order and the first integer of each row is greater than the last integer of the previous row, the matrix can be visualized as a single flattened, sorted array. This allows us to use binary search to achieve an O(log(m*n)) time complexity.
# Explanation:
  1. Matrix and Binary Search Setup :
    • Each element in the matrix can be uniquely indexed using two coordinates, namely row and column indices.
    • Since the matrix elements are sorted in a row-major order, it's feasible to map a 2D index to a 1D index, which is conducive to applying binary search.
  2. Defining Matrix Dimensions :
    • We determine the number of rows
      m
      and columns
      n
      from the matrix.
  3. Binary Search Implementation :
    • Initialize two pointers
      left
      and
      right
      to the beginning and end of the hypothetical 1D array that the 2D matrix represents.
    • Calculate the middle index
      mid
      and map it back to its 2D coordinates (row and column).
    • Compare the middle element with the target. If it matches, return
      True
      .
    • Adjust the search range based on whether the middle element is less than or greater than the target.
    • If pointers cross without finding the element, return
      False
      .
    Here’s the pseudocode that encapsulates the above steps:
    # Pseudocode with Comments:
                                                
    # Given a matrix and a target value
    # Initialize matrix dimensions
    rows = number of rows in matrix
    columns = number of columns in matrix
    
    # Initialize search boundary pointers
    left = 0
    right = (rows * columns) - 1
    
    # Conduct binary search
    while left <= right:
    # Calculate the middle index
    mid = left + (right - left) // 2
    
    # Map mid index back to 2D coordinates
    row_index = mid // columns
    column_index = mid % columns
    mid_element = matrix[row_index][column_index]
    
    # Compare the middle element with the target value
    if mid_element == target:
    return True # Target found
    elif mid_element < target:
    left = mid + 1 # Adjust the search to the right half
    else:
    right = mid - 1 # Adjust the search to the left half
    
    # Target is not found in the matrix
    return False
    
                                            
    # Detailed Steps in Pseudocode:
  4. Matrix Initialization :
    • rows = len(matrix)
      calculates the number of rows in the matrix.
    • columns = len(matrix[0])
      calculates the number of columns in the matrix.
  5. Binary Search Initialization :
    • left = 0
      sets the left boundary to the start of the 1D representation of the matrix.
    • right = (rows * columns) - 1
      sets the right boundary to the end of the 1D representation.
  6. Binary Search Loop :
    • Mid Calculation :
      mid = left + (right - left) // 2
      calculates the middle index.
    • Mapping to 2D Coordinates :
      • row_index = mid // columns
        maps the middle index to the corresponding row.
      • column_index = mid % columns
        maps the middle index to the corresponding column.
      • mid_element = matrix[row_index][column_index]
        retrieves the middle element from the matrix.
    • Comparison :
      • If
        mid_element == target
        : Return
        True
        (target found).
      • If
        mid_element < target
        : Move the
        left
        pointer to
        mid + 1
        to search the right half.
      • If
        mid_element > target
        : Move the
        right
        pointer to
        mid - 1
        to search the left half.
  7. End Condition :
    • If the loop exits without finding the target, return
      False
      .
This method effectively leverages binary search with adjustments for matrix-based indexing, ensuring an efficient solution with O(log(m*n)) time complexity.