Each row is sorted and starts above the last row's end, so the grid is one sorted list in disguise: binary search it with row and column math.
▼The problem
LeetCode 74 (Medium). An m × n integer matrix has every row sorted, and the first value of each row is greater than the last value of the row before it. Given target, return true if it is in the matrix, else false.
Examples (LeetCode's): matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 → true (walked through in scene 7) and the same matrix, target = 13 → false (scene 8).
The solution
def searchMatrix(matrix, target):
m, n = len(matrix), len(matrix[0])
lo, hi = 0, m * n - 1
while lo <= hi:
mid = (lo + hi) // 2
v = matrix[mid // n][mid % n]
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return FalseTranscript
Search a 2D Matrix. Every row is sorted, and every row starts higher than the row above it ends. Is a target in it? Return true or false.
Three rows of four: one, three, five, seven; ten, eleven, sixteen, twenty; twenty-three, thirty, thirty-four, sixty. Three is there: true. Thirteen belongs between eleven and sixteen, but it's missing: false.
Checking every cell takes m times n looks: twelve. Binary searching each row is quicker, m times log n, but still visits every row.
Here's the key. Read the rows in order, and you get one sorted list of twelve numbers. So binary search the positions, zero to eleven, without building the list.
Divide a position by n, the row length: the quotient is its row, the remainder its column. Position seven: seven divided by four is one, remainder three. Row one, column three: twenty.
In code, low starts at zero, and high at m times n, minus one. Take the middle, map it to its cell, and compare. Equal: return true. Too small: move low right. Too big: move high left. If they cross, return false.
Find three. Middle five: row one, column one, eleven. Too big, so high drops to four. Middle two: five, too big. Middle zero: one, too small. Middle one: three. Found it in four looks.
Now thirteen. Middle five: eleven, too small, so low jumps to six. Middle eight: twenty-three, too big. Middle six: sixteen, too big. Low passes high: false.
Each look halves the range: time O of log of m times n. Twelve cells take at most four looks; a million, twenty. Space is constant: low, high and middle.
One sorted list, one binary search, mapped back to the grid. That's Search a 2D Matrix.