Search a 2D Matrix II
Medium
Topics
matrix has every row sorted ascending left to right, and every column sorted ascending top to bottom. Return true if target is present.
Note what is not guaranteed: the rows are not a single sorted sequence end to end. A row can start below the previous row’s last value.
Example 1
5 gives true, at the shaded cell. Every row increases left to right and every column increases top to bottom, which is less than it sounds: the rows do not run on from each other — row 1 starts below where the row above it ended — so the cells read in order are not a sorted sequence.Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 5 Output: true Explanation: 5 sits at row 1, column 1.
Example 2
15 gives false, because no cell holds it.Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 15 Output: false Explanation: 15 is between 14 and 16 but appears nowhere.
Example 3
Input: matrix = [[-5]], target = -5 Output: true Explanation: A single cell, which is both the smallest and largest value.
Constraints
- 1 <= matrix.length, matrix[0].length <= 300
- -10^9 <= matrix[i][j] <= 10^9
- Each row is sorted ascending
- Each column is sorted ascending
- -10^9 <= target <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Flattening the matrix and searching it as one sorted array is the tempting move and it is wrong here. The rows are individually sorted but not continuous with each other — row 2 starts at 3 while row 1 ends at 12 — so the flattened sequence is not sorted and a halving search on it is meaningless. This is the difference between this problem and Search a 2D Matrix.
What the two sortings do give is a corner where the comparison is decisive. Stand at the top-right cell. Everything to its left in that row is smaller; everything below it in that column is larger. So one comparison always eliminates an entire row or an entire column:
If the cell is larger than the target, the target cannot be anywhere in that column — every cell below is even larger — so step left. If the cell is smaller, the target cannot be anywhere in that row — every cell to the left is even smaller — so step down.
Each step retires one row or one column for good, so the walk visits at most rows + columns cells. The bottom-left corner works identically with the directions swapped; the top-left and bottom-right corners do not work, because there both neighbours move the same way and no comparison eliminates anything.
Approach
- Start at row
0, columncols - 1, the top-right cell. - While the position is inside the matrix, compare the cell with the target.
- Equal: return
true. - Cell greater than the target: decrement the column, discarding that column.
- Cell less than the target: increment the row, discarding that row.
- Falling off the edge means the target is absent, so return
false.
Walkthrough
matrix = [[1, 4, 7,11],
[2, 5, 8,12],
[3, 6, 9,16],
[10,13,14,17]]
target = 5
start top-right at (0,3) = 11
11 > 5 -> column 3 is out, step left
(0,2) = 7
7 > 5 -> column 2 is out, step left
(0,1) = 4
4 < 5 -> row 0 is out, step down
(1,1) = 5
found, true
target = 15
(0,3)=11 < 15 -> down
(1,3)=12 < 15 -> down
(2,3)=16 > 15 -> left
(2,2)=9 < 15 -> down
(3,2)=14 < 15 -> down
row 4 does not exist, so false
why not the top-left corner
at (0,0) = 1 with target 5, both right and down lead
to larger values, so a "greater than" result tells you
nothing about which way to go.Complexity
- Time — O(rows + cols): every step removes one row or one column permanently.
- Space — O(1): two indices.
Common Pitfalls
- Flattening and running a halving search. That needs the rows to be continuous, which this problem does not promise.
- Starting at the top-left or bottom-right corner, where a comparison does not eliminate anything.
- Running a halving search per row. It is correct, and slower than the corner walk at
logper row. - Writing the loop bound as
c > 0, which never examines column 0. - Moving both indices on one comparison. Exactly one moves.
Full Solution — all languages
class Solution:
def searchMatrix(self, matrix, target):
rows, cols = len(matrix), len(matrix[0])
# Top-right: left is strictly smaller, below is strictly larger, so one
# comparison always retires a whole row or a whole column.
r, c = 0, cols - 1
while r < rows and c >= 0:
value = matrix[r][c]
if value == target:
return True
if value > target:
c -= 1 # nothing in this column can be the target
else:
r += 1 # nothing in this row can be the target
return Falseimport java.util.*;
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length, cols = matrix[0].length;
int r = 0, c = cols - 1;
while (r < rows && c >= 0) {
int value = matrix[r][c];
if (value == target) return true;
if (value > target) c--;
else r++;
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = (int)matrix.size(), cols = (int)matrix[0].size();
int r = 0, c = cols - 1;
while (r < rows && c >= 0) {
int value = matrix[r][c];
if (value == target) return true;
if (value > target) c--;
else r++;
}
return false;
}
};/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/ var searchMatrix = function(matrix, target) {
const rows = matrix.length, cols = matrix[0].length;
let r = 0, c = cols - 1;
while (r < rows && c >= 0) {
const value = matrix[r][c];
if (value === target) return true;
if (value > target) c--;
else r++;
}
return false;
};