Search A 2D Matrix Ii

To solve this coding challenge, you must understand the structure of the input matrix and utilize its sorted properties to search for a target value efficiently. The matrix is sorted both row-wise and column-wise. This distinctive sorting property makes it possible to utilize a strategic search method instead of a straightforward linear search.

Explanation

Given an
m x n
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, the challenge is to determine if a given target value exists within the matrix or not.
The sorted properties of the matrix allow us to employ a search strategy that leverages these restrictions to eliminate large portions of the matrix that cannot contain the target:
  1. Start the search from the top-right corner of the matrix.
  2. Compare the current element with the target:
    • If the current element is equal to the target, return
      True
      .
    • If the current element is less than the target, move down to the next row because all elements in the current row to the left are smaller and can be ignored.
    • If the current element is greater than the target, move left to the previous column because all elements in the current column below are greater and can be ignored.
  3. Repeat the comparison until you either find the target (return
    True
    ) or exhaust the search area (return
    False
    ).
  4. This method is efficient because it narrows down the search space progressively by eliminating either a row or a column at each comparison step.
    Detailed Steps in Pseudocode:
  5. Initialization :
    • If the matrix is empty or the first row of the matrix is empty, return
      False
      (no need to continue).
    • Set the starting point at the top-right corner of the matrix (
      row = 0
      ,
      col = last column index
      ).
  6. Search Process :
    • While the current position is within the bounds of the matrix:
      • Compare the current element with the target:
        • If
          matrix[row][col]
          is equal to the target, return
          True
          .
        • If
          matrix[row][col]
          is less than the target, increment the row index (move down).
        • If
          matrix[row][col]
          is greater than the target, decrement the column index (move left).
    • If the loop ends without finding the target, return
      False
      .
    Pseudocode with Comments:
                                                
    # Check if the matrix is empty or has no columns.
    if matrix is empty OR first row of matrix is empty:
    return False
    
    # Start from the top-right corner of the matrix.
    row = 0
    col = number of columns in the matrix - 1
    
    # Loop while the current position is within the bounds of the matrix.
    while row < number of rows in matrix AND col >= 0:
    # If the current element is equal to the target, return True.
    if matrix[row][col] == target:
    return True
    # If the current element is less than the target, move to the next row.
    elif matrix[row][col] < target:
    row = row + 1
    # If the current element is greater than the target, move to the previous column.
    else:
    col = col - 1
    
    # If we exit the loop, the target is not in the matrix, so return False.
    return False
    
                                            
    Step-by-Step Explanation:
  7. Check Matrix : First, ensure that the matrix is not empty and that it contains at least one column.
  8. Initial Position : Start the search at the top-right corner, because this position offers the best insight due to the sorted nature of the matrix.
  9. Comparison and Movement :
    • If the element at the current position matches the target, the search is successful, and the function returns
      True
      .
    • If the element is smaller than the target, it implies that the target cannot be in the same row (to the left), so we move down to the next row.
    • If the element is larger than the target, it implies that the target cannot be in the same column (below), so we move left to the previous column.
  10. Exit Condition : The while loop ensures that the search continues as long as we are within the boundaries of the matrix. If the loop terminates, it indicates that the target is not present in the matrix, and the function returns
    False
    .
This strategy ensures an efficient search with a time complexity of O(m + n), where m is the number of rows and n is the number of columns, due to the elimination process in each step of the loop.