⬅ Previous Topic
Search in Row and Column-wise Sorted MatrixNext Topic ⮕
Matrix Median⬅ Previous Topic
Search in Row and Column-wise Sorted MatrixNext Topic ⮕
Matrix MedianTopic Contents
You are given a 2D matrix of size N × M
where:
Your task is to determine whether a given target
value exists in the matrix or not.
If the target
is found, return true
; otherwise, return false
.
start = 0
, end = N * M - 1
.start ≤ end
:mid = (start + end) / 2
.mid
to row = mid / M
and col = mid % M
.mat[row][col]
with target
.target < mat[row][col]
, move left (end = mid - 1
).target > mat[row][col]
, move right (start = mid + 1
).public class MatrixSearch {
public static boolean searchMatrix(int[][] mat, int target) {
int rows = mat.length;
int cols = mat[0].length;
int start = 0;
int end = rows * cols - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
int row = mid / cols; // Map 1D index to 2D row
int col = mid % cols; // Map 1D index to 2D col
if (mat[row][col] == target) {
return true;
} else if (mat[row][col] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return false;
}
public static void main(String[] args) {
int[][] mat = {
{1, 4, 7},
{8, 11, 15},
{17, 20, 23}
};
int target = 11;
System.out.println("Found? " + searchMatrix(mat, target));
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | When the target is found in the first mid calculation. |
Average Case | O(log(N * M)) | The binary search reduces the search space by half in each iteration over the virtual flattened array. |
Average Case | O(log(N * M)) | All elements are searched using binary search till the last comparison. |
O(1)
Explanation: No extra space is used; the algorithm uses a constant number of variables.
⬅ Previous Topic
Search in Row and Column-wise Sorted MatrixNext Topic ⮕
Matrix MedianYou 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.