Algo-Sim › Matrix & Bit Manipulation
Search a 2D Matrix II
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Rows and columns are sorted separately: start at the top-right corner and drop one row or one column per comparison, O(m + n).
Problem
Every row of the m × n matrix is sorted left to right and every column is sorted top to bottom (a row does not have to start above the previous row’s end). Return true if target is in the matrix.
Constraints
- 1 ≤ m, n ≤ 300
- -10⁹ ≤ matrix[i][j], target ≤ 10⁹
- Rows and columns are sorted ascending
Edge cases to test
- Target missing
- Single row or column
- Duplicates along a row
Follow-up questions
- Why start at the top-right (or bottom-left)?
- From there one direction only increases and the other only decreases, so each comparison discards a whole row or column: O(m + n).
- Can it be O(log)?
- Not in general: a diagonal of independent values needs Ω(n) checks. Binary search per row is O(m log n), better only when m is much smaller than n.
Solution
Java
public boolean searchMatrix(int[][] matrix, int target) {
int row = 0, col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
int value = matrix[row][col];
if (value == target) return true;
if (value > target) col--;
else row++;
}
return false;
}Python
def search_matrix(matrix, target):
row, col = 0, len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
value = matrix[row][col]
if value == target: return True
if value > target: col -= 1
else: row += 1
return FalseC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>> &matrix, int target) {
int row = 0, col = matrix[0].size() - 1;
while (row < (int)matrix.size() && col >= 0) {
int value = matrix[row][col];
if (value == target) return true;
if (value > target) col--;
else row++;
}
return false;
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (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)