AlgoInsight

DSA problem

Search a 2D Matrix II

MediumBinary SearchPattern: Binary Searchtop600AmazonMicrosoftGoogleFacebook

Write an efficient algorithm that searches for a value target in an m × n integer matrix matrix. This matrix has the following properties: integers in each row are sorted in ascending order from left to right, and integers in each column are sorted in ascending order from top to bottom. Note: rows and columns are sorted independently — unlike in "Search a 2D Matrix", there is no global row-major ordering.

Without the strict row-major property, naive flattening fails. A row-by-row or column-by-column binary search costs O(m log n) or O(n log m), which is acceptable but not the cleanest. The textbook solution uses a single pointer that walks along an antidiagonal direction.

Start at the top-right corner (row = 0, col = n - 1). The element there is the largest in its row and the smallest in its column. So:

Each step eliminates an entire row or column. There are m + n rows and columns combined, so the search runs in O(m + n) time and O(1) space. This beats both naive O(m log n) row search and the simpler flattened approach (which is not even applicable here).

Examples

Example 1
Input: 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 = 5
Output: true
Explanation: Starting at (0, 4) = 15, move left to (0, 3) = 11, then (0, 2) = 7, then (0, 1) = 4 < 5 so move down to (1, 1) = 5. Found.
Example 2
Input: 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 = 20
Output: false
Explanation: The walk eventually steps off the bottom or right edge without finding 20.
Example 3
Input: matrix = [[1]], target = 0
Output: false
Explanation: Single-cell matrix not equal to target; the pointer steps off immediately.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searchmatrixdivide-and-conquer

Browse all DSA problems