# LeetCode – Search a 2D Matrix II (Java)

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

For example, consider the following 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]
]
```

Given target = 5, return true.

Java Solution 1

In a naive approach, we can use the matrix boundary to reduce the search space. Here is a simple recursive implementation.

```public boolean searchMatrix(int[][] matrix, int target) { int i1=0; int i2=matrix.length-1; int j1=0; int j2=matrix[0].length-1;   return helper(matrix, i1, i2, j1, j2, target); }   public boolean helper(int[][] matrix, int i1, int i2, int j1, int j2, int target){   if(i1>i2||j1>j2) return false;   for(int j=j1;j<=j2;j++){ if(target < matrix[i1][j]){ return helper(matrix, i1, i2, j1, j-1, target); }else if(target == matrix[i1][j]){ return true; } }   for(int i=i1;i<=i2;i++){ if(target < matrix[i][j1]){ return helper(matrix, i1, i-1, j1, j2, target); }else if(target == matrix[i][j1]){ return true; } }   for(int j=j1;j<=j2;j++){ if(target > matrix[i2][j]){ return helper(matrix, i1, i2, j+1, j2, target); }else if(target == matrix[i2][j]){ return true; } }   for(int i=i1;i<=i2;i++){ if(target > matrix[i][j2]){ return helper(matrix, i1, i+1, j1, j2, target); }else if(target == matrix[i][j2]){ return true; } }   return false; }```

Java Solution 2

Time Complexity: O(m + n)

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

### 3 thoughts on “LeetCode – Search a 2D Matrix II (Java)”

1. there is a simple , logN solution

find element X

step1

start 0,0, lets find in first row elements bigger than X

start 0.0 , lets find in first column element bigger than X

Cross of row and column will give us point (m, n) somewhere in matrix, it is down/right element

step2

from point (m,n), lets find elements in row M that smaller then X,

from point (m,n), lets find elements in column N that smaller then X,
cross of row and column will give us up/left element (F, G)

——-
so we have sub matrix between (f,g) and (m,n)

do over step1

2. it is sorted and NO binary search?.. THERE MUST BE BETTER SOLUTION.!

lets value =16

by binary search in 0column, we can find smallest row, that bigger than value. so its row before 18.

after for each column FROM 0 , check hi/low per column if value can be w/in,
found 11-17 , 15-24, and can use binary search again.

3. You don’t have condition for initial check.

if(matrix == null || matrix.length == 0)
{
return false;
}

This should make Java solution 2 – acceptable in leetcode.