Search a 2D Matrix II in Python

When working with a 2D matrix where rows and columns are sorted in ascending order, we need an efficient search algorithm. This problem is commonly known as "Search a 2D Matrix II" and can be solved optimally using a staircase search approach.

Matrix Properties

The matrix has these important characteristics:

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

Here's an example 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

Algorithm Approach

The key insight is to start from the top-right corner (or bottom-left corner) of the matrix. This position allows us to eliminate either a row or column with each comparison:

  • If current element equals target ? return True
  • If current element is greater than target ? move left (eliminate column)
  • If current element is less than target ? move down (eliminate row)

Implementation

def search_matrix(matrix, target):
    if not matrix or not matrix[0]:
        return False
    
    rows, cols = len(matrix), len(matrix[0])
    row, col = 0, cols - 1  # Start from top-right corner
    
    while row < rows and col >= 0:
        current = matrix[row][col]
        
        if current == target:
            return True
        elif current > target:
            col -= 1  # Move left
        else:
            row += 1  # Move down
    
    return False

# Test with the example matrix
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]
]

print("Searching for 5:", search_matrix(matrix, 5))
print("Searching for 20:", search_matrix(matrix, 20))
print("Searching for 14:", search_matrix(matrix, 14))
Searching for 5: True
Searching for 20: False
Searching for 14: True

How It Works

Let's trace through searching for target = 5:

  1. Start at top-right: matrix[0][4] = 15. Since 15 > 5, move left
  2. matrix[0][3] = 11. Since 11 > 5, move left
  3. matrix[0][2] = 7. Since 7 > 5, move left
  4. matrix[0][1] = 4. Since 4
  5. matrix[1][1] = 5. Found target! Return True

Alternative Class-based Implementation

class Solution:
    def searchMatrix(self, matrix, target):
        if not matrix or not matrix[0]:
            return False
        
        rows, cols = len(matrix), len(matrix[0])
        row, col = 0, cols - 1
        
        while row < rows and col >= 0:
            if matrix[row][col] == target:
                return True
            elif matrix[row][col] > target:
                col -= 1
            else:
                row += 1
        
        return False

# Test the solution
solution = Solution()
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]]
print(solution.searchMatrix(matrix, 5))
print(solution.searchMatrix(matrix, 20))
True
False

Time and Space Complexity

  • Time Complexity: O(m + n) where m is rows and n is columns
  • Space Complexity: O(1) as we only use constant extra space

Conclusion

The staircase search algorithm efficiently searches a sorted 2D matrix by starting from a corner and eliminating rows or columns based on comparisons. This approach achieves O(m + n) time complexity, making it optimal for this problem.

Updated on: 2026-03-25T08:02:15+05:30

723 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements