← DiffPush

Search in sorted matrix

Baseline Binary Search · 2D Arrays O(log(m * n)) · O(1)

One Flat Index over a Serialized Grid

A telemetry archive serializes its readings into a grid where every row continues the previous one in ascending order - flattening the grid would yield one sorted list. Storage limits forbid materializing that flattened copy, so the lookup must address cells directly through arithmetic on a virtual flat index.

Input: An m x n matrix where each row is sorted and the first integer of each row is greater than the last integer of the previous row, plus an integer target.

Output: true when target appears in the matrix, otherwise false.

Constraints

Examples

Example 1

Input: {"matrix":[[1,3,5,7],[10,11,16,20],[23,30,34,60]],"target":3}
Output: true
The virtual flat index resolves to the cell in row 0, column 1, which holds 3.

Example 2

Input: {"matrix":[[1,3,5,7],[10,11,16,20],[23,30,34,60]],"target":13}
Output: false
13 falls between serialized blocks and never matches any probed cell, so the search reports false.

Solve this in your browser →

Also on LeetCode ↗