Skip to content

visual walkthrough

Search a 2D Matrix

MediumClassic Binary SearchReported at: MetaAmazonMicrosoft+7

Treat a matrix as a flattened sorted array.

Solve on LeetCode

The idea

Each row is sorted and each row starts after the previous one ends, so reading row by row gives one long sorted list.

Binary search that list without building it: position p lives at row p / C, column p mod C.

Complexity

approachtimespace
Check every cellO(R · C)O(1)
Binary search as one listO(log(R · C))O(1)

More walkthroughs