Search in 2D Matrix in DSA Go - 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 as the matrix gets bigger?
Analyze the time complexity of the following code snippet.
func searchMatrix(matrix [][]int, target int) bool {
rows := len(matrix)
cols := len(matrix[0])
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
if matrix[i][j] == target {
return true
}
}
}
return false
}
This code checks every element in the matrix until it finds the target or finishes checking all.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the matrix.
- How many times: The outer loop runs once per row, and the inner loop runs once per column, so total checks = rows x 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(rows x 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 very fast like O(log n)."
[OK] Correct: This code checks every element without using the sorted order, 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 properties
The matrix rows are sorted and each row's first element 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 single sorted array, binary search can be used to efficiently find the target.Final Answer:
Treat the 2D matrix as a sorted 1D array and use binary search -> Option CQuick Check:
Sorted matrix + binary search = Treat the 2D matrix as a sorted 1D array and use binary search [OK]
- Searching each row linearly wastes time
- Using hash map wastes extra space
- Starting from bottom-left works only for different matrix types
Solution
Step 1: Understand Go 2D slice initialization
In Go, a 2D slice is a slice of slices. We first create the outer slice with length 3, then initialize each inner slice with length 4.Step 2: Check each option
matrix := make([][]int, 3); for i := range matrix { matrix[i] = make([]int, 4) } correctly creates a 3x4 2D slice. matrix := [][]int{{3,4},{1,2,3},{4,5,6,7}} is irregular and not fixed size. matrix := make([]int, 3*4) creates a 1D slice. matrix := [3][4]int{} creates a fixed array, not a slice.Final Answer:
matrix := make([][]int, 3); for i := range matrix { matrix[i] = make([]int, 4) } -> Option DQuick Check:
2D slice init with make + loop = matrix := make([][]int, 3); for i := range matrix { matrix[i] = make([]int, 4) } [OK]
- Using make only once creates 1D slice
- Confusing arrays and slices
- Initializing inner slices incorrectly
matrix := [][]int{
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50},
}
target := 5
found := false
rows := len(matrix)
cols := len(matrix[0])
left, right := 0, rows*cols-1
for left <= right {
mid := (left + right) / 2
val := matrix[mid/cols][mid%cols]
if val == target {
found = true
break
} else if val < target {
left = mid + 1
} else {
right = mid - 1
}
}
fmt.Println(found)Solution
Step 1: Understand binary search on 2D matrix
The code treats the matrix as a 1D sorted array and uses binary search with index mapping mid/cols and mid%cols to access elements.Step 2: Trace the search for target 5
Target 5 is at matrix[0][2]. The binary search will find it and set found to true.Final Answer:
true -> Option AQuick Check:
Binary search finds 5 = true [OK]
- Incorrect index mapping causing wrong element access
- Off-by-one errors in binary search boundaries
- Not breaking loop when found
func searchMatrix(matrix [][]int, target int) bool {
rows := len(matrix)
cols := len(matrix[0])
left, right := 0, rows*cols
for left <= right {
mid := (left + right) / 2
val := matrix[mid/cols][mid%cols]
if val == target {
return true
} else if val < target {
left = mid + 1
} else {
right = mid - 1
}
}
return false
}Solution
Step 1: Check initialization of right pointer
Since indices go from 0 to rows*cols - 1, right should be rows*cols - 1, not rows*cols.Step 2: Understand impact of wrong right value
Setting right to rows*cols causes out-of-bounds access when mid equals rows*cols, leading to runtime error.Final Answer:
right should be initialized to rows*cols - 1 -> Option AQuick Check:
Right boundary off by one causes error = right should be initialized to rows*cols - 1 [OK]
- Using rows*cols instead of rows*cols - 1 for right
- Swapping row and column indices
- Incorrect loop condition causing infinite loop
Solution
Step 1: Analyze matrix properties
Since rows are sorted but rows are not strictly increasing overall, the matrix is not globally sorted.Step 2: Choose search strategy
Binary search on entire matrix won't work. Binary search on each row is O(m log n). Starting from top-right corner and moving left/down is O(m+n) and efficient.Final Answer:
Start from top-right corner and move left/down based on comparison -> Option BQuick Check:
Partial row sorting + top-right search = Start from top-right corner and move left/down based on comparison [OK]
- Assuming full matrix is sorted for binary search
- Flattening and sorting wastes time
- Ignoring matrix properties leads to wrong approach
Ready to prove it?
Pass the test and this pattern moves unknown
