Skip to Content

Search a 2d matrix II

Home | Coding Interviews | Searching and Sorting | Search a 2d matrix II

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

Integers in each row are sorted in ascending from left to right.

Integers in each column are sorted in ascending from top to bottom.

public boolean searchMatrix(int[][] matrix, int target) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
        return false;

    int n = matrix.length, m = matrix[0].length;
    int i = 0, j = m - 1;
    
    while (i < n && j >= 0) {
        int num = matrix[i][j];
        
        if (num == target)
            return true;
        else if (num > target)
            j--;
        else
            i++;
    }
    
    return false;
}

Posted by Jamie Meyer 19 days ago