Write an efficient algorithm that searches for a value target in an m x n integer matrix. This matrix has the following properties:


Test Cases

Example 1:

1 3 5 7
10 11 16 20
23 30 34 60
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true

Example 2:

1 3 5 7
10 11 16 20
23 30 34 60
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false

Solution

bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target){
    int row = 0, col = *matrixColSize-1;
    while(row < matrixSize && col >= 0) {
        int cell = matrix[row][col];
        if (cell == target) return true;
        if (cell < target) {
            row++;
        } else {
            col--;
        }
    }
    return false;
}
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size(), m = matrix[0].size();
        int row = 0, col = m-1;
        while(row < n && col >= 0) {
            int cell = matrix[row][col];
            if (cell == target) return true;
            if (cell < target) {
                row++;
            } else {
                col--;
            }
        }
        return false;
    }
};
package search_a_2d_matrix

func searchMatrix(matrix [][]int, target int) bool {
	n := len(matrix)
	m := len(matrix[0])
	row := 0
	col := m-1
	for row < n && col >=0 {
		cell := matrix[row][col]
		if cell == target {
			return true
		}
		if cell < target {
			row++
		} else {
			col--
		}
	}
	return false
}
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int n = matrix.length, m = matrix[0].length;
        int row = 0, col = m-1;
        while(row < n && col >= 0) {
            int cell = matrix[row][col];
            if (cell == target) return true;
            if (cell < target) {
                row++;
            } else {
                col--;
            }
        }
        return false;
    }
}
from typing import List


class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        n, m = len(matrix), len(matrix[0])
        row, col = 0, m - 1
        while row < n and col >= 0:
            cell = matrix[row][col]
            if cell == target:
                return True
            if cell < target:
                row += 1
            else:
                col -= 1
        return False
Time Complexity: O(mn)
Space Complexity: O(1)