74. Search a 2D Matrix
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to efficiently search for a target value in an m x n matrix. The matrix has two key properties: each row is sorted, and the first element of any row is greater than the last element of the preceding row. These two properties combined imply that if we flatten the matrix into a 1D array (by concatenating rows), the resulting array is sorted in non-decreasing order. For example, [[1,3,5],[10,11,16],[23,30,34]] can be viewed as [1,3,5,10,11,16,23,30,34]. This transforms the problem into a search on a sorted array. The required time complexity of O(log(m * n)) strongly suggests that a binary search algorithm is the way to go.
Solution
Search a 2D Matrix in Python
class Solution:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
# Handle empty matrix case
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
# Treat the matrix as a flattened sorted array and perform binary search
left, right = 0, m * n - 1
while left <= right:
# Calculate mid index. Python's integers handle large numbers, so direct average is fine.
# Using // for integer division.
mid = (left + right) // 2
# Map the 1D mid index back to 2D matrix coordinates
row = mid // n
col = mid % n
mid_val = matrix[row][col]
if mid_val == target:
return True # Target found
elif mid_val < target:
# Search in the right half
left = mid + 1
else:
# Search in the left half
right = mid - 1
return False # Target not found
Search a 2D Matrix in Java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
// Handle empty matrix case
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int m = matrix.length;
int n = matrix[0].length;
// Treat the matrix as a flattened sorted array and perform binary search
int left = 0, right = m * n - 1;
while (left <= right) {
// Calculate mid index to avoid potential overflow
int mid = left + (right - left) / 2;
// Map the 1D mid index back to 2D matrix coordinates
int row = mid / n;
int col = mid % n;
int midVal = matrix[row][col];
if (midVal == target) {
return true; // Target found
} else if (midVal < target) {
// Search in the right half
left = mid + 1;
} else {
// Search in the left half
right = mid - 1;
}
}
return false; // Target not found
}
}
Search a 2D Matrix in C++
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
// Handle empty matrix case
if (matrix.empty() || matrix[0].empty()) {
return false;
}
int m = matrix.size();
int n = matrix[0].size();
// Treat the matrix as a flattened sorted array and perform binary search
int left = 0, right = m * n - 1;
while (left <= right) {
// Calculate mid index to avoid potential overflow
int mid = left + (right - left) / 2;
// Map the 1D mid index back to 2D matrix coordinates
int row = mid / n;
int col = mid % n;
int mid_val = matrix[row][col];
if (mid_val == target) {
return true; // Target found
} else if (mid_val < target) {
// Search in the right half
left = mid + 1;
} else {
// Search in the left half
right = mid - 1;
}
}
return false; // Target not found
}
};
Search a 2D Matrix in TypeScript
function searchMatrix(matrix: number[][], target: number): boolean {
// Handle empty matrix case
if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
return false;
}
const m = matrix.length;
const n = matrix[0].length;
// Treat the matrix as a flattened sorted array and perform binary search
let left = 0;
let right = m * n - 1;
while (left <= right) {
// Calculate mid index to avoid potential overflow
const mid = Math.floor(left + (right - left) / 2);
// Map the 1D mid index back to 2D matrix coordinates
const row = Math.floor(mid / n);
const col = mid % n;
const midVal = matrix[row][col];
if (midVal === target) {
return true; // Target found
} else if (midVal < target) {
// Search in the right half
left = mid + 1;
} else {
// Search in the left half
right = mid - 1;
}
}
return false; // Target not found
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.