Search in 2D Matrix in DSA Javascript - Time & Space Complexity
We want to understand how long it takes to find a number in a 2D matrix.
Specifically, how the search time grows as the matrix gets bigger.
Analyze the time complexity of the following code snippet.
function searchMatrix(matrix, target) {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === target) {
return true;
}
}
}
return false;
}
This code checks each element in the matrix one by one to find the target number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the matrix.
- How many times: The outer loop runs for each row, and the inner loop runs for each column in that row.
As the matrix size grows, the number of checks grows with the total number of elements.
| Input Size (n x m) | Approx. Operations |
|---|---|
| 10 x 10 | 100 checks |
| 100 x 100 | 10,000 checks |
| 1000 x 1000 | 1,000,000 checks |
Pattern observation: The operations grow roughly by the total number of elements, so doubling rows and columns quadruples work.
Time Complexity: O(n * m)
This means the time to search grows proportionally to the total number of elements in the matrix.
[X] Wrong: "Since the matrix is sorted, we can find the target in constant time."
[OK] Correct: Even if sorted, this code checks every element one by one, so it still takes time proportional to all elements in the worst case.
Understanding how nested loops affect time helps you explain and improve search methods in real problems.
"What if we used binary search on each row instead of checking every element? How would the time complexity change?"
Practice
Solution
Step 1: Understand matrix properties
Each row and column is sorted ascending, so top-right element is a good start to decide direction.Step 2: Use top-right corner to guide search
If target is less than current element, move left; if greater, move down.Final Answer:
Start from top-right corner and move left or down based on comparison -> Option DQuick Check:
Top-right start = efficient search [OK]
- Searching all elements one by one wastes time
- Starting from bottom-left without clear logic
- Using binary search on each row ignores column sorting
matrix in JavaScript?Solution
Step 1: Identify correct loop ranges
Outer loop runs over rows (matrix.length), inner loop over columns (matrix[0].length).Step 2: Check element equality with strict equality
Use === for exact match and return true if found.Final Answer:
for(let i=0; i -> Option BQuick Check:
Correct loop ranges and strict equality [OK]
- Swapping row and column lengths in loops
- Using == instead of === causing type coercion
- Looping inner loop with wrong length causing errors
const matrix = [
[1, 4, 7, 11],
[2, 5, 8, 12],
[3, 6, 9, 16],
[10, 13, 14, 17]
];
const target = 5;
function searchMatrix(matrix, target) {
let row = 0;
let 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;
}
console.log(searchMatrix(matrix, target));Solution
Step 1: Start from top-right element
Initial position is matrix[0][3] = 11, compare with target 5.Step 2: Move left since 11 > 5, now at matrix[0][2] = 7
7 > 5, move left again to matrix[0][1] = 4.Step 3: 4 < 5, move down to matrix[1][1] = 5
Found target 5, return true.Final Answer:
true -> Option CQuick Check:
Top-right search finds 5 = true [OK]
- Starting from wrong corner causing wrong moves
- Not updating row or column correctly
- Returning false too early without full search
function searchMatrix(matrix, target) {
let row = matrix.length - 1;
let col = 0;
while(row >= 0 && col < matrix[0].length) {
if(matrix[row][col] === target) return true;
else if(matrix[row][col] < target) row--;
else col++;
}
return false;
}Solution
Step 1: Analyze movement logic
Starting at bottom-left, if current < target, should move right (col++), else move up (row--).Step 2: Check conditions in code
Code moves row-- when current < target, which is wrong; it should move col++ instead.Final Answer:
The directions to move row and col are swapped in conditions -> Option AQuick Check:
Correct move directions fix search [OK]
- Swapping row and column moves
- Wrong initial position for search
- Incorrect loop condition causing infinite loop
Solution
Step 1: Understand time complexities
Full traversal is slow (O(m*n)), binary search per row is better but still costly.Step 2: Use top-right start to count efficiently
Moving left/down lets you skip rows or columns, counting matches in O(m+n) time.Final Answer:
Start from top-right and move left/down counting matches (O(m+n)) -> Option AQuick Check:
Top-right traversal counts efficiently [OK]
- Using full traversal wasting time
- Flattening matrix losing sorted structure
- Binary search per row misses column info
Ready to prove it?
Pass the test and this pattern moves unknown
