Search a sorted matrix
HardGiven a sorted
matrix
of numbers of size m x n
, and a target
number, write a function that determines if the target
number exists in the matrix
.For example, if your function recieves the following 3x3 matrix and target number:
matrix = [[1, 3, 8],[9, 21, 24],[25, 28, 32]]target = 7
Your function should return
False
.Given the same matrix, if the
target
is 21
, your function should return True
.Note that every row is sorted. Each row starts with a number that is greater than the last number from the previous row.
Try it
Before you look at the solution, try to code it yourself.
Solution
Time and Space Complexity
Since we cut the problem in half in each iteration, the time complexity is
O(log n)
.There is no additional space required. So the space complexity constant
O(1)
.5 Essential Sorting & Searching Coding Interview Problems
Master Sorting & Searching by trying the coding challenges below.
- 1.Merge intervalsMedium
- 2.Kth largest in arrayMedium
- 3.Intersection of ArraysMedium
- 4.Search sorted matrixHard
- 5.Search row & col sorted matrixHard