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 along rows and columns

Medium · Target 20 minutes · Binary search · Type asked atAmazonGoogleGoldman Sachs

An m × n matrix has every row sorted in increasing order from left to right and every column sorted in increasing order from top to bottom. Rows may overlap in value. Return true if target is in the matrix and false otherwise.

Examples

InputOutputWhy
matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5true
the same matrix, target = 20false

Constraints

  • 1 ≤ m, n ≤ 300
  • −10⁹ ≤ matrix[i][j], target ≤ 10⁹

Hints

Hint 1

Reading order is not sorted here, so the previous problem's trick fails. Which cell has the useful property that one comparison discards something whole?

Hint 2

The top-right cell is the largest in its row and the smallest in its column.

Hint 3

If it is larger than target, its whole column is too large: move left. If smaller, its whole row is too small: move down.

Where people lose marks

  • Starting at the top-left corner, which is the smallest in both its row and its column: a comparison there rules out nothing.
  • Flattening the matrix and binary searching it as in the previous problem: reading order is not sorted here.
  • Moving the wrong way after a comparison; say out loud which line the comparison eliminates.
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.