By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
"This problem appears in 1 out of every 3 onsite interviews—master it, and you prove you can reduce 2D search to 1D binary search, a skill that separates senior candidates from the rest."
Before tackling this problem, ensure you understand: 1. Binary Search – How to search in a sorted 1D array in O(log n) time. 2. Matrix Traversal – How to convert between 2D indices (row, col) and a 1D index. 3. Edge Cases in Search – Handling empty matrices, single-row/column matrices, and duplicates.
(row, col)
Repeat this mental checklist for every "Search a 2D Matrix" problem:
Are there empty rows/columns? Edge cases (1x1, 1xN, Nx1)?
Choose the Right Technique
If unsorted, use BFS/DFS (but expect O(mn) time).
Convert 2D to 1D (if using Binary Search)
For a matrix of size m x n, the 1D index mid maps to:
m x n
mid
row = mid // n
col = mid % n
Implement Binary Search (if applicable)
left = 0
right = m n - 1
While left <= right:
left <= right
mid = left + (right - left) // 2
matrix[row][col]
target
left
right
Handle Edge Cases
False
Duplicates → Decide if first/last occurrence is needed.
Optimize for Time & Space
Space: O(1) for most approaches, O(mn) for BFS/DFS.
Test with Examples
Problem: Write an efficient algorithm to search for a value target in an m x n matrix where: - Integers in each row are sorted in ascending order. - The first integer of each row is greater than the last integer of the previous row.
Solution (Flattened Binary Search):
def searchMatrix(matrix, target): if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) left, right = 0, m n - 1 while left <= right: mid = left + (right - left) // 2 row, col = mid // n, mid % n if matrix[row][col] == target: return True elif matrix[row][col] < target: left = mid + 1 else: right = mid - 1 return False
Time Complexity: O(log(mn)) Space Complexity: O(1)
Why This Works: - The matrix is fully sorted (row-wise + first element of each row > last element of previous row). - We treat it as a 1D sorted array and apply binary search.
Problem: Write an efficient algorithm to search for a value target in an m x n matrix where: - Integers in each row are sorted in ascending order. - Integers in each column are sorted in ascending order. - No guarantee that first element of row > last element of previous row.
Solution (Staircase Search):
def searchMatrix(matrix, target): if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) row, col = 0, n - 1 # Start from top-right while row < m and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 # Move down (larger values) else: col -= 1 # Move left (smaller values) return False
Time Complexity: O(m + n) Space Complexity: O(1)
Why This Works: - The matrix is sorted row-wise and column-wise, but not fully sorted. - Starting from top-right, we can eliminate a row or column in each step.
Problem: Same as LeetCode 240, but the matrix may contain duplicates. Return True if target exists, False otherwise.
True
Solution (Modified Staircase Search):
def searchMatrix(matrix, target): if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) row, col = 0, n - 1 # Start from top-right while row < m and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 else: col -= 1 return False
Why This Works: - Duplicates do not break the staircase search because we still eliminate rows/columns correctly. - If matrix[row][col] < target, moving down is safe (all elements to the left are smaller). - If matrix[row][col] > target, moving left is safe (all elements below are larger).
matrix[row][col] < target
matrix[row][col] > target
Follow-up: Return All Occurrences If the interviewer asks for all positions of target:
def searchMatrixAllOccurrences(matrix, target): if not matrix or not matrix[0]: return [] m, n = len(matrix), len(matrix[0]) row, col = 0, n - 1 result = [] while row < m and col >= 0: if matrix[row][col] == target: result.append((row, col)) # Move left to find duplicates in the same row temp_col = col - 1 while temp_col >= 0 and matrix[row][temp_col] == target: result.append((row, temp_col)) temp_col -= 1 # Move down to find duplicates in the same column temp_row = row + 1 while temp_row < m and matrix[temp_row][col] == target: result.append((temp_row, col)) temp_row += 1 row += 1 col -= 1 elif matrix[row][col] < target: row += 1 else: col -= 1 return result
Time Complexity: O(m + n + k), where k is the number of occurrences. Space Complexity: O(k) (for storing results).
k
mid // m
mid // n
left < right
if not matrix or not matrix[0]
"Alright, let’s lock this in. When you see ‘Search a 2D Matrix,’ follow this playbook:
This pattern shows up constantly in interviews. Nail it, and you’re one step closer to that offer. Now go practice!
Now go crush that interview! ?
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.