Search in 2D Matrix in DSA Java - Time & Space Complexity
We want to understand how the time to find a number in a 2D matrix grows as the matrix gets bigger.
Specifically, how many steps does it take to search through the matrix?
Analyze the time complexity of the following code snippet.
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == target) {
return true;
}
}
}
return false;
}
This code checks every element in the matrix one by one until it finds the target or finishes checking all elements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the matrix.
- How many times: The outer loop runs once for each row, and the inner loop runs once for each column in that row.
As the matrix size grows, the number of elements to check grows with the total number of rows times columns.
| Input Size (rows x cols) | Approx. Operations |
|---|---|
| 10 x 10 | 100 checks |
| 100 x 100 | 10,000 checks |
| 1000 x 1000 | 1,000,000 checks |
Pattern observation: The number of checks grows quickly as the matrix gets bigger, multiplying rows and columns.
Time Complexity: O(rows * cols)
This means the time to search grows directly with the total number of elements in the matrix.
[X] Wrong: "Since the matrix is sorted, searching is always fast like O(log n)."
[OK] Correct: This code checks every element without using the sorted order to skip parts, so it still takes time proportional to all elements.
Understanding how nested loops affect time helps you explain and improve search methods in real problems.
"What if we use binary search on each row instead of checking every element? How would the time complexity change?"
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
