Search in 2D Matrix
MediumAcc. 90.2%
+35 XP 15
The Efficient Grid Search
Searching through a massive grid can be slow ($O(N cdot M)$). However, if the grid is "perfectly sorted"—where each row is sorted and its first element is greater than the previous row's last—we can treat the entire grid as one long sorted line. This allows us to use Binary Search to find any value instantly.
The Assignment
Your mission is to find the target in the sorted grid. Your function receives a matrix and a target value.
- Treat the matrix as a flattened array where the total length is
rows * cols. - Use Binary Search logic with
low = 0andhigh = length - 1. - To find the grid coordinates from a "flat" index:
row = Math.floor(index / cols)col = index % cols
- Print true if the target exists, otherwise print false.
01EXAMPLE 1
Input
matrix=[[1, 3], [10, 20]], target=3Output
trueExplanation: 3 is in row 0.
Constraints
- O(log(m*n)) time complexity.
MatrixSearching
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
matrix[[1,3,5],[10,11,16]]
target3
Expected Output
true
Click RUN to test your solution