Search a Matrix with Ordered Rows and Columns
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Given a rectangular integer matrix and an integer target, return whether the matrix contains the target. Each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom.
Use these ordering properties to search efficiently.
bool searchMatrix(vector<vector<int>>& matrix, int target)
matrix = [[-3,0,4,9],[-1,2,6,12],[1,5,8,15]]
target = 6
Output: true
The value 6 is at row 1, column 2, using zero-based indices.
matrix = [[-3,0,4,9],[-1,2,6,12],[1,5,8,15]]
target = 7
Output: false
1 <= matrix.length <= 300
.
1
and
300
columns.
-1000000000 <= matrix[i][j] <= 1000000000
.
-1000000000 <= target <= 1000000000
.
There is no guarantee that reading an entire row and then the next row gives one globally sorted sequence. Return only a boolean; no target position is required. A uniqueness condition on matrix entries is not provided.