⬅ Previous Topic
Search in a Sorted 2D MatrixNext Topic ⮕
Find Target in 2D Matrix⬅ Previous Topic
Search in a Sorted 2D MatrixNext Topic ⮕
Find Target in 2D MatrixTopic Contents
You are given a 2D matrix where each row and each column is sorted in non-decreasing order. Your task is to search for a given target value in this matrix.
You need to determine whether the target value exists in the matrix or not. Return true
if it exists, else return false
.
The matrix is not fully sorted overall, but it has a special property:
row = 0
, col = M - 1
.row < N
and col ≥ 0
:mat[row][col] == target
, return true
.mat[row][col] > target
, move left by doing col--
.mat[row][col] < target
, move down by doing row++
.false
.public class MatrixSearch {
public static boolean searchMatrix(int[][] mat, int target) {
int n = mat.length;
int m = mat[0].length;
int row = 0, col = m - 1;
while (row < n && col >= 0) {
if (mat[row][col] == target) {
return true;
} else if (mat[row][col] > target) {
col--; // Move left
} else {
row++; // Move down
}
}
return false;
}
public static void main(String[] args) {
int[][] mat = {
{1, 4, 7},
{2, 5, 8},
{3, 6, 9}
};
int target = 5;
System.out.println("Element found: " + searchMatrix(mat, target));
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | When the target is found at the starting cell (top-right corner). |
Average Case | O(N + M) | In each step, we either eliminate a row or a column, leading to at most N + M steps. |
Average Case | O(N + M) | In the worst case, the search visits one full row and one full column without finding the target. |
O(1)
Explanation: Only a few extra variables are used for row and column tracking, with no additional memory.
⬅ Previous Topic
Search in a Sorted 2D MatrixNext Topic ⮕
Find Target in 2D MatrixYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.