Program to find a target value inside given matrix or not in Python

Suppose we have a 2D matrix where each row and column is sorted in non-decreasing order. We need to check whether a given target value is present inside it or not.

So, if the input is like ?

2 4 30
3 4 31
6 6 32

And target = 31, then the output will be True.

Approach

To solve this efficiently, we can start from the top-right corner of the matrix and move either left or down based on the comparison with the target value ?

  • Start from the top-right corner (first row, last column)
  • If current element equals target, return True
  • If current element is greater than target, move left (decrease column)
  • If current element is less than target, move down (increase row)
  • If we go out of bounds, return False

Example

class Solution:
    def solve(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
ob = Solution()
matrix = [[2, 4, 30], [3, 4, 31], [6, 6, 32]]
target = 31
result = ob.solve(matrix, target)
print(f"Target {target} found: {result}")
Target 31 found: True

How It Works

Let's trace through the algorithm with our example ?

def search_matrix_step_by_step(matrix, target):
    rows, cols = len(matrix), len(matrix[0])
    row, col = 0, cols - 1
    
    print(f"Searching for {target} in matrix:")
    for r in matrix:
        print(r)
    print()
    
    while row < rows and col >= 0:
        current = matrix[row][col]
        print(f"Position ({row}, {col}): {current}")
        
        if current == target:
            print(f"Found {target}!")
            return True
        elif current > target:
            print(f"{current} > {target}, move left")
            col -= 1
        else:
            print(f"{current} < {target}, move down")
            row += 1
    
    print(f"{target} not found")
    return False

# Trace the execution
matrix = [[2, 4, 30], [3, 4, 31], [6, 6, 32]]
search_matrix_step_by_step(matrix, 31)
Searching for 31 in matrix:
[2, 4, 30]
[3, 4, 31]
[6, 6, 32]

Position (0, 2): 30
30 < 31, move down
Position (1, 2): 31
Found 31!

Multiple Examples

Let's test with different target values ?

def find_target(matrix, target):
    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 with multiple targets
matrix = [[2, 4, 30], [3, 4, 31], [6, 6, 32]]
targets = [2, 4, 31, 32, 5, 35]

for target in targets:
    found = find_target(matrix, target)
    print(f"Target {target}: {'Found' if found else 'Not Found'}")
Target 2: Found
Target 4: Found
Target 31: Found
Target 32: Found
Target 5: Not Found
Target 35: Not Found

Time and Space Complexity

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

Conclusion

The algorithm efficiently searches a sorted 2D matrix by starting from the top-right corner and eliminating either a row or column in each step. This approach takes advantage of the sorted property to achieve O(m + n) time complexity.

Updated on: 2026-03-25T12:39:29+05:30

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements