Algo-Sim › Matrix & Bit Manipulation
Search a 2D Matrix
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Find a target in a matrix whose rows read as one sorted list: binary search over the flattened index, mapping k to (k / n, k % n).
Problem
Each row of the m × n matrix is sorted, and each row starts with a value larger than the last value of the row above. Return true if target is in the matrix, in O(log(m·n)) time.
Constraints
- 1 ≤ m, n ≤ 100
- -10⁴ ≤ matrix[i][j], target ≤ 10⁴
- Reading the rows in order gives one sorted list
Edge cases to test
- Target smaller than the first cell or larger than the last
- 1 × n or m × 1
- Target in the last row
Follow-up questions
- Why one binary search instead of two?
- Reading the rows end to end gives one sorted list of m·n values, so one search over index k with (k / n, k % n) is O(log mn).
- What if only rows and columns are sorted separately?
- Start at the top-right and drop a row or column per step: O(m + n) (LC 240).
Solution
Java
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int lo = 0, hi = m * n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int value = matrix[mid / n][mid % n];
if (value == target) return true;
if (value < target) lo = mid + 1;
else hi = mid - 1;
}
return false;
}Python
def search_matrix(matrix, target):
m, n = len(matrix), len(matrix[0])
lo, hi = 0, m * n - 1
while lo <= hi:
mid = (lo + hi) // 2
value = matrix[mid // n][mid % n]
if value == target:
return True
if value < target:
lo = mid + 1
else:
hi = mid - 1
return FalseC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>> &matrix, int target) {
int m = int(matrix.size()), n = int(matrix[0].size());
int lo = 0, hi = m * n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int value = matrix[mid / n][mid % n];
if (value == target)
return true;
if (value < target)
lo = mid + 1;
else
hi = mid - 1;
}
return false;
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)