Find a Value in a Matrix Sorted Like a Flattened Array
Solve this Problemm × n matrix where every row is sorted in ascending order, and the first number of each row is greater than the last number of the previous row — so reading it row by row produces one fully sorted sequence. Given an integer target, return whether it exists anywhere in the matrix.
Solve it in O(log(m × n)) time by binary-searching the matrix as if it were a single flattened, sorted array — no need to actually flatten it.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ matrix.length, matrix[0].length ≤ 100 - ◆
-10⁴ ≤ matrix[i][j], target ≤ 10⁴ - ◆
Every row is sorted in ascending order - ◆
The first integer of each row is greater than the last integer of the previous row
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public boolean searchMatrix(int[][] matrix, int target) { |
| 3 | int m = matrix.length, n = matrix[0].length; |
| 4 | int lo = 0, hi = m * n - 1; |
| 5 | while (lo <= hi) { |
| 6 | int mid = lo + (hi - lo) / 2; |
| 7 | int val = matrix[mid / n][mid % n]; |
| 8 | if (val == target) { |
| 9 | return true; |
| 10 | } else if (val < target) { |
| 11 | lo = mid + 1; |
| 12 | } else { |
| 13 | hi = mid - 1; |
| 14 | } |
| 15 | } |
| 16 | return false; |
| 17 | } |
| 18 | } |
| 19 |
34011Treat the matrix as one sorted array of 12 elements (indices 0-11) and binary-search it directly, mapping each flattened index back to a cell.
Approach & Solutions
Brute Force — Scan Every Cell
BruteCheck every cell, row by row. It's correct on any matrix, sorted or not, but it ignores the very specific guarantee this problem gives you — that reading the matrix row by row produces one fully sorted sequence — which is what lets binary search skip almost the whole matrix.
O(m × n)O(1)1class Solution {
2 public boolean searchMatrix(int[][] matrix, int target) {
3 for (int i = 0; i < matrix.length; i++) {
4 for (int j = 0; j < matrix[0].length; j++) {
5 if (matrix[i][j] == target) return true;
6 }
7 }
8 return false;
9 }
10}Optimal — Binary Search on the Flattened Index
OptimalBecause every row continues where the previous one left off, reading the matrix row-major (left to right, top to bottom) produces one sorted array of m × n elements — you just never materialize it. Binary search that virtual array directly: a flattened index mid maps back to matrix[mid / n][mid % n].
O(log(m × n))O(1)1class Solution {
2 public boolean searchMatrix(int[][] matrix, int target) {
3 int m = matrix.length, n = matrix[0].length;
4 int lo = 0, hi = m * n - 1;
5 while (lo <= hi) {
6 int mid = lo + (hi - lo) / 2;
7 int val = matrix[mid / n][mid % n];
8 if (val == target) {
9 return true;
10 } else if (val < target) {
11 lo = mid + 1;
12 } else {
13 hi = mid - 1;
14 }
15 }
16 return false;
17 }
18}