Search a 2D Matrix
Medium
Topics
You are given an m x n matrix where each row is sorted ascending and the first integer of each row is greater than the last integer of the previous row. Return true if target is present.
Example 1
target 3
Each row is sorted ascending, and every row begins above the previous row’s last value — so the ordering runs continuously from the top-left cell to the bottom-right. The question is only whether 3 appears: it does, so
true.2D grid — one row per line.
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true
Example 2
The question is only whether 13 appears: it does not, so
false.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 Output: false
Constraints
- 1 <= m, n <= 100
- -10^4 <= matrix[i][j], target <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
The two sorting guarantees mean the whole matrix is one sorted sequence read row by row. So you can binary search it as if it were a flat array of length m*n, mapping an index back to (row, col).
Approach
- Binary search over indices 0 .. m*n - 1.
- Map mid to
matrix[mid // n][mid % n]. - Compare and move lo/hi as in ordinary binary search.
Dry Run
matrix 1 3 5 7
10 11 16 20
23 30 34 60
Rows are sorted and each row starts above the previous row's end, so the matrix is
one sorted list of 12 values with an index that has to be decoded.
target 3
lo=0 hi=11 mid=5 -> (1,1) = 11 too big, hi=4
lo=0 hi=4 mid=2 -> (0,2) = 5 too big, hi=1
lo=0 hi=1 mid=0 -> (0,0) = 1 too small, lo=1
lo=1 hi=1 mid=1 -> (0,1) = 3 found
target 13
lo=0 hi=11 mid=5 -> (1,1) = 11 too small, lo=6
lo=6 hi=11 mid=8 -> (2,0) = 23 too big, hi=7
lo=6 hi=7 mid=6 -> (1,2) = 16 too big, hi=5
lo passed hi -> not present
answer true, then false
The decode is `mid // n` and `mid % n` where n is the COLUMN count -- the number
of cells per row. Using m, the row count, is wrong whenever the matrix is not
square: here target 7 comes back false and target 60 raises IndexError.
`mid = (lo + hi) // 2` is the textbook form and is correct as written at this
problem's bounds. In Java or C++ it is the line that bites once lo + hi passes
2^31 - 1 and wraps negative; `lo + (hi - lo) // 2` is the habit worth keeping,
same answer and same cost. Python's integers are arbitrary precision, so it is a
non-issue there.
This works only because the rows are globally sorted. For the variant where rows
and columns are each sorted but rows do not chain, the staircase walk from the
top-right is the right answer instead.Complexity
- Time — O(log(m*n)): a single binary search over all cells.
- Space — O(1): constant extra space.
Common Pitfalls
- Use the column count n (not m) to decode mid into row and column. On the page's 3x4 matrix, decoding with m makes target 7 return false and target 60 raise
IndexError. mid = (lo + hi) / 2is the textbook form, and in Java or C++ it is the one that bites: the momentlo + hipasses2^31 - 1it wraps negative and the index flies out of range. This problem’s bounds never get close, so the code above is correct as written, butlo + (hi - lo) / 2is the habit worth keeping — same answer, same cost, no overflow. Python’s integers are arbitrary precision, so it is a non-issue there.
Full Solution — all languages
class Solution:
def searchMatrix(self, matrix, target):
m,n=len(matrix),len(matrix[0])
lo,hi=0,m*n-1
while lo<=hi:
mid=(lo+hi)//2
val=matrix[mid//n][mid%n]
if val==target: return True
if val<target: lo=mid+1
else: hi=mid-1
return Falseimport java.util.*;
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m=matrix.length,n=matrix[0].length,lo=0,hi=m*n-1;
while(lo<=hi) {
int mid=(lo+hi)/2,val=matrix[mid/n][mid%n];
if(val==target)return true;
if(val<target)lo=mid+1;
else hi=mid-1;
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m=matrix.size(),n=matrix[0].size(),lo=0,hi=m*n-1;
while(lo<=hi) {
int mid=(lo+hi)/2,val=matrix[mid/n][mid%n];
if(val==target)return true;
if(val<target)lo=mid+1;
else hi=mid-1;
}
return false;
}
};/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/ var searchMatrix = function(matrix, target) {
const m=matrix.length,n=matrix[0].length;
let lo=0,hi=m*n-1;
while(lo<=hi) {
const mid=(lo+hi)>>1,val=matrix[Math.floor(mid/n)][mid%n];
if(val===target)return true;
if(val<target)lo=mid+1;
else hi=mid-1;
}
return false;
};