Search in 2D Matrix in DSA Typescript - Time & Space Complexity
We want to understand how long it takes to find a number in a 2D matrix.
How does the search time grow when the matrix gets bigger?
Analyze the time complexity of the following code snippet.
function searchMatrix(matrix: number[][], target: number): boolean {
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] === target) {
return true;
}
}
}
return false;
}
This code checks every element in the matrix until it finds the target or finishes all elements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the matrix.
- How many times: For each row, it checks every column element, so total checks = number of rows x number of columns.
As the matrix size grows, the number of checks grows with the total number of elements.
| Input Size (rows x cols) | Approx. Operations |
|---|---|
| 10 x 10 = 100 | About 100 checks |
| 100 x 100 = 10,000 | About 10,000 checks |
| 1000 x 1000 = 1,000,000 | About 1,000,000 checks |
Pattern observation: The operations grow proportionally to the total number of elements in the matrix.
Time Complexity: O(m x n)
This means the time to search grows directly with the number of rows (m) times the number of columns (n).
[X] Wrong: "The search will always be fast because we stop when we find the target."
[OK] Correct: In the worst case, the target might be at the very end or not present, so the code checks every element, making the time grow with the whole matrix size.
Understanding this helps you explain how searching in a grid works and why sometimes it takes longer when the data grows.
"What if the matrix rows and columns were sorted, and we used a smarter search? How would the time complexity change?"
Practice
Solution
Step 1: Understand matrix properties
Since each row and column is sorted ascending, the top-right element is the largest in its row and smallest in its column.Step 2: Use top-right corner to decide movement
If the target is less than the current element, move left; if greater, move down. This efficiently narrows search space.Final Answer:
Start from the top-right corner and move left or down based on comparison -> Option BQuick Check:
Top-right corner search = Start from the top-right corner and move left or down based on comparison [OK]
- Starting from bottom-left without adjusting moves correctly
- Searching row by row wastes time
- Using binary search on rows ignores column sorting
Solution
Step 1: Check matrix type declaration
TypeScript 2D array is declared as number[][]. const matrix: number[][] = [[1,2,3],[4,5,6],[7,8,9]];.Step 2: Validate matrix structure
const matrix: number[][] = [[1,2,3],[4,5,6],[7,8,9]]; has uniform rows with 3 elements each, valid for a matrix. const matrix: number[][] = [[1,2,3],[4,5],[6,7,8,9]]; has rows of different lengths, which is allowed but less common for matrices.Final Answer:
const matrix: number[][] = [[1,2,3],[4,5,6],[7,8,9]]; -> Option CQuick Check:
Proper 2D array syntax = const matrix: number[][] = [[1,2,3],[4,5,6],[7,8,9]]; [OK]
- Using single array for 2D matrix
- Incorrect type declaration like number[] for 2D
- Mixing array elements without nested arrays
const matrix = [
[1, 4, 7, 11],
[2, 5, 8, 12],
[3, 6, 9, 16],
[10, 13, 14, 17]
];
function searchMatrix(matrix: number[][], target: number): boolean {
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, 5));Solution
Step 1: Start search from top-right corner
Initial position is row=0, col=3 (value 11). Since 11 > 5, move left to col=2 (value 7).Step 2: Compare and move accordingly
7 > 5, move left to col=1 (value 4). 4 < 5, move down to row=1, col=1 (value 5). Found target 5, return true.Final Answer:
true -> Option DQuick Check:
Search finds 5 = true [OK]
- Not updating row and col correctly
- Returning false too early
- Confusing row and column indices
function searchMatrix(matrix: number[][], target: number): boolean {
let row = 0;
let col = matrix.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;
}Solution
Step 1: Check initialization of col variable
col is set to matrix.length - 1, which is number of rows minus one, but columns count is matrix[0].length.Step 2: Correct col initialization
col should be matrix[0].length - 1 to point to the last column index in the first row.Final Answer:
col should be initialized to matrix[0].length - 1, not matrix.length - 1 -> Option AQuick Check:
col init must match columns count = col should be initialized to matrix[0].length - 1, not matrix.length - 1 [OK]
- Using rows count for column index
- Wrong loop conditions causing out-of-bounds
- Returning true instead of false when not found
function searchMatrix(matrix: number[][], target: number): number[] {
let row = 0;
let col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] === target) {
// What to return here?
} else if (matrix[row][col] > target) {
col--;
} else {
row++;
}
}
// What to return if not found?
}Solution
Step 1: Return position when target found
Inside the if condition, return the current indices as [row, col] to indicate target position.Step 2: Return [-1, -1] if target not found
After the loop ends without finding target, return [-1, -1] to indicate absence.Final Answer:
Return [row, col] inside if, and [-1, -1] after loop -> Option AQuick Check:
Return position or [-1, -1] if missing = Return [row, col] inside if, and [-1, -1] after loop [OK]
- Swapping row and col in return
- Returning boolean instead of position
- Returning wrong default value when not found
Ready to prove it?
Pass the test and this pattern moves unknown
