What if you could find any number in a giant grid without checking every single spot?
Why Search in 2D Matrix in DSA Java?
Imagine you have a big spreadsheet with rows and columns full of numbers. You want to find if a certain number is there. You start checking each cell one by one, moving left to right, top to bottom.
This manual way is very slow and tiring. If the spreadsheet is huge, it takes a long time to check every cell. You might also lose track or make mistakes while searching.
Using a smart search method for a 2D matrix helps you find the number quickly without checking every cell. It uses the order in rows and columns to skip many cells, saving time and effort.
for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == target) return true; } } return false;
int row = 0, col = matrix[0].length - 1; while (row < matrix.length && col >= 0) { if (matrix[row][col] == target) return true; else if (matrix[row][col] > target) col--; else row++; } return false;
This method lets you find any number in a sorted 2D matrix quickly and confidently, even if the matrix is very large.
Think of a library catalog arranged by shelves (rows) and books (columns) sorted by title. You can quickly find a book by skipping shelves or books that are too early or too late alphabetically.
Manual search checks every cell, which is slow for big matrices.
Smart search uses matrix order to skip unnecessary checks.
It saves time and reduces errors when searching.
Practice
Solution
Step 1: Understand matrix sorting property
Each row is sorted and the first element of a row is greater than the last element of the previous row, so the entire matrix can be seen as a sorted list.Step 2: Apply binary search on the matrix
By treating the matrix as a 1D sorted array, binary search can be used efficiently to find the target.Final Answer:
Treat the 2D matrix as a sorted 1D array and apply binary search -> Option AQuick Check:
Matrix sorted row-wise = binary search [OK]
- Searching each row linearly wastes time
- Using hash map wastes extra space
- Starting from bottom-left only works for different matrix types
rows * cols?Solution
Step 1: Understand safe mid calculation
Usinglow + (high - low) / 2prevents integer overflow compared to(low + high) / 2.Step 2: Check other options
int mid = (low - high) / 2; and D do not correctly calculate mid index for binary search.Final Answer:
int mid = low + (high - low) / 2; -> Option DQuick Check:
Safe mid calculation = low + (high - low) / 2 [OK]
- Using (low + high) / 2 can cause overflow
- Using subtraction incorrectly for mid
- Multiplying low and high is wrong
int[][] matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,60}};, what will be the output?public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
int low = 0, high = rows * cols - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int midValue = matrix[mid / cols][mid % cols];
if (midValue == target) return true;
else if (midValue < target) low = mid + 1;
else high = mid - 1;
}
return false;
}
System.out.println(searchMatrix(matrix, 5));Solution
Step 1: Understand matrix and target
The matrix contains 5 at position (0,2). The binary search checks mid values correctly by converting 1D mid to 2D indices.Step 2: Trace binary search steps
Binary search finds 5 and returns true.Final Answer:
true -> Option AQuick Check:
5 found in matrix = true [OK]
- Using wrong index conversion for mid
- Confusing row and column indices
- Returning false before full search
public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
int low = 0, high = rows * cols;
while (low <= high) {
int mid = low + (high - low) / 2;
int midValue = matrix[mid / cols][mid % cols];
if (midValue == target) return true;
else if (midValue < target) low = mid + 1;
else high = mid - 1;
}
return false;
}Solution
Step 1: Check high initialization
High should be the last valid index, which is rows * cols - 1, not rows * cols (which is out of bounds).Step 2: Verify other parts
Mid calculation and indexing are correct; loop condition low <= high is standard for binary search.Final Answer:
The high index should be rows * cols - 1, not rows * cols -> Option BQuick Check:
High index off by one causes error [OK]
- Setting high to rows * cols causes out-of-bounds
- Changing loop condition incorrectly
- Miscomputing mid index
Solution
Step 1: Understand matrix property
Rows are sorted but no guarantee that next row's first element is greater than previous row's last element, so treating as 1D sorted array is invalid.Step 2: Choose search method
Starting from top-right corner, move left if current > target, move down if current < target, efficiently narrows search.Final Answer:
Start from top-right corner and move left/down based on comparison -> Option CQuick Check:
Top-right corner search = efficient for partially sorted matrix [OK]
- Applying 1D binary search wrongly
- Searching each row fully wastes time
- Using linear search is slow
Ready to prove it?
Pass the test and this pattern moves unknown
