top of page
Search

Search a 2D Matrix II

Updated: Mar 25, 2021

Write an efficient algorithm that searches for a target value in an m x n integer matrix. The 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.


Example 1:

Input: 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]], target = 5
Output: true

Example 2:

Input: 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]], target = 20
Output: false

Constraints:

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= n, m <= 300

  • -109 <= matix[i][j] <= 109

  • All the integers in each row are sorted in ascending order.

  • All the integers in each column are sorted in ascending order.

  • -109 <= target <= 109

Solution:

Iterative:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int i=matrix.length-1,j=0;
        while(i>=0 && j<=matrix[0].length-1)
        {
            if(matrix[i][j]==target) return true;
            else
            {
                if(matrix[i][j]>target) i--;
                else
                    j++;
            }
        }
        return false;
    }
}

Recursive:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
       return helper(matrix,target,matrix.length-1,0);
    }
    
    public boolean helper(int[][] matrix,int target,int i,int j)
    {
        if(i<0 || j<0 || i>matrix.length-1 || j>matrix[0].length-1) return false;
        if(matrix[i][j]==target) return true;
        return (matrix[i][j]>target)? helper(matrix,target,i-1,j):helper(matrix,target,i,j+1);
    }
}


28 views0 comments

Recent Posts

See All

Minimum Deletions to Make Character Frequencies Unique

A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The f

Smallest String With A Given Numeric Value

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.

bottom of page