Search a 2D Matrix
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Each row of the matrix is sorted and each row starts above the last value of the previous row. Does a target exist?
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1If you wrote all rows one after another, would the result be sorted?
- Hint 2Position p of the long line is row p // columns and column p % columns.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A cinema numbers its seats 1, 2, 3 ... straight through the rows: row 1 has seats 1-4, row 2 has seats 5-8, and so on. If a friend asks "where is seat 9?", you do not walk row by row. Seat 9 is in row (9 ÷ 4) and column (9 mod 4). The whole hall acts like one long numbered line, so you can binary-search the seat numbers.
- The obvious way
Scan every cell: O(rows x columns).
- The key insight
Pretend the matrix is one list of length rows x columns and binary search it. The value at position p is matrix[p // columns][p % columns]. No real flattening is needed.
- The algorithm
- Treat the cells as positions 0 to rows x columns - 1.
- Take the middle position; turn it into (row, column) with divide and remainder.
- Read that cell and compare with the target, then discard half as in plain binary search.
Watch it run
Examplematrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
Middle position 5 is row 1, column 1: value 11. Bigger than 3, so keep the left part.
positions 0 to 4 remain
Where people slip
- Divide by the number of COLUMNS, not rows, when turning a position into a row.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def search_matrix(matrix, target):
rows, columns = len(matrix), len(matrix[0])
low, high = 0, rows * columns - 1
while low <= high:
middle = (low + high) // 2
value = matrix[middle // columns][middle % columns] # position -> (row, column)
if value == target:
return True
if value < target:
low = middle + 1
else:
high = middle - 1
return FalseNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.