Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Search a matrix sorted in reading order

Medium · Target 15 minutes · Binary search · Type asked atMicrosoftAmazonBloomberg

An m × n matrix of integers has two properties: each row is sorted in increasing order, and the first value of each row is greater than the last value of the row above. Return true if target is in the matrix and false otherwise, in O(log(m × n)) time.

Examples

InputOutputWhy
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3true
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13false

Constraints

  • 1 ≤ m, n ≤ 100
  • −10⁴ ≤ matrix[i][j], target ≤ 10⁴

Hints

Hint 1

Write the matrix out row after row. What do you get?

Hint 2

A sorted list of m × n values. Position k in that list is row k / n, column k % n.

Hint 3

Run the exact-match search over k in [0, m × n − 1], reading matrix[k / n][k % n] at each step.

Where people lose marks

  • Dividing by the number of rows instead of the number of columns.
  • Using this method on a matrix whose rows and columns are sorted but whose rows overlap: reading order is then not sorted. That is the next problem.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.