Fatskills
Practice. Master. Repeat.
Study Guide: How to Solve: Search a 2D Matrix (FAANG-Level Guide)
Source: https://www.fatskills.com/leetcode/chapter/how-to-solve-search-a-2d-matrix-faang-level-guide

How to Solve: Search a 2D Matrix (FAANG-Level Guide)

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~7 min read

How to Solve: Search a 2D Matrix (FAANG-Level Guide)


? Introduction

"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."


? WHAT YOU NEED TO KNOW FIRST

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.


? KEY TECHNIQUES & PATTERNS

Technique / Pattern When to Use Quick Example
Flattened Binary Search Matrix is sorted row-wise and column-wise (or fully sorted). Treat the 2D matrix as a 1D sorted array and apply binary search.
Two-Pointer Search Matrix is sorted row-wise but not necessarily column-wise. Start from top-right or bottom-left and eliminate rows/columns.
Staircase Search Matrix is sorted in both rows and columns (but not necessarily fully sorted). Compare target with current element and move diagonally.
Row Elimination + Binary Search Matrix is sorted row-wise, and first/last elements of rows are sorted. Binary search to find the correct row, then binary search within the row.
BFS/DFS (if unsorted) Matrix is unsorted (rare in interviews). Traverse all elements (O(mn) time).
Hash Set (if duplicates) Matrix has duplicates (follow-up). Store seen elements in a set to avoid reprocessing.

? STEP-BY-STEP FRAMEWORK

Repeat this mental checklist for every "Search a 2D Matrix" problem:

  1. Clarify the Matrix Properties
  2. Is the matrix sorted row-wise? Column-wise? Both?
  3. Are there duplicates? If yes, how should they be handled?
  4. Are there empty rows/columns? Edge cases (1x1, 1xN, Nx1)?

  5. Choose the Right Technique

  6. If fully sorted (row-wise + column-wise), use Flattened Binary Search.
  7. If row-wise sorted + first/last elements sorted, use Row Elimination + Binary Search.
  8. If sorted in rows and columns but not fully, use Staircase Search.
  9. If unsorted, use BFS/DFS (but expect O(mn) time).

  10. Convert 2D to 1D (if using Binary Search)

  11. For a matrix of size m x n, the 1D index mid maps to:

    • row = mid // n
    • col = mid % n
  12. Implement Binary Search (if applicable)

  13. Initialize left = 0, right = m n - 1.
  14. While left <= right:

    • mid = left + (right - left) // 2
    • Convert mid to (row, col).
    • Compare matrix[row][col] with target.
    • Adjust left or right accordingly.
  15. Handle Edge Cases

  16. Empty matrix → Return False.
  17. Single-row or single-column matrix → Treat as 1D array.
  18. Duplicates → Decide if first/last occurrence is needed.

  19. Optimize for Time & Space

  20. Time: O(log(mn)) for binary search, O(m + n) for staircase search.
  21. Space: O(1) for most approaches, O(mn) for BFS/DFS.

  22. Test with Examples

  23. Test with:
    • Target present in first/last row.
    • Target not present.
    • Single-row/single-column matrix.
    • Duplicates (if allowed).

? WORKED EXAMPLES

Example 1 – Basic (LeetCode 74: Search a 2D Matrix)

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.


Example 2 – Medium (LeetCode 240: Search a 2D Matrix II)

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.


Example 3 – Hard/Follow-up (Search in a Sorted Matrix with Duplicates)

Problem: Same as LeetCode 240, but the matrix may contain duplicates. Return True if target exists, False otherwise.

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

Time Complexity: O(m + n) Space Complexity: O(1)

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).

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).


❌ Common Mistakes

Mistake Why it Happens Correct Approach
Assuming the matrix is fully sorted Candidates see "sorted" and assume binary search works directly. Check if first element of row > last element of previous row. If not, use staircase search.
Incorrect 2D to 1D conversion Using mid // m instead of mid // n for row calculation. For m x n matrix, row = mid // n, col = mid % n.
Off-by-one errors in binary search Using left < right instead of left <= right. Always use left <= right for inclusive bounds.
Not handling empty matrix Forgetting to check if not matrix or not matrix[0]. Always check for empty input first.
Using BFS/DFS for sorted matrices Overcomplicating with O(mn) solutions. If matrix is sorted, binary search or staircase search is always better.

? INTERVIEW TrapS

Trap How to Spot it How to Avoid it
"What if the matrix is unsorted?" Interviewer asks for a follow-up with unsorted input. Clarify: "If unsorted, we must use BFS/DFS (O(mn) time)."
"How would you handle duplicates?" Interviewer adds duplicates to the problem. Use staircase search (works with duplicates) or hash set (if tracking all occurrences).
"Can you do better than O(m + n)?" Interviewer pushes for optimization. If matrix is fully sorted, flattened binary search (O(log(mn))) is better.

? 1-Minute Recap

"Alright, let’s lock this in. When you see ‘Search a 2D Matrix,’ follow this playbook:

  1. Clarify the matrix properties – Is it sorted row-wise? Column-wise? Both? Are there duplicates?
  2. Choose the right technique
  3. If fully sorted, flatten it and use binary search (O(log(mn))).
  4. If row-wise + column-wise sorted, use staircase search (O(m + n)) from top-right.
  5. If unsorted, fall back to BFS/DFS (O(mn)).
  6. Convert 2D to 1D correctly – For binary search, row = mid // n, col = mid % n.
  7. Handle edge cases – Empty matrix, single-row/column, duplicates.
  8. Test with examples – Target in first/last row, not present, duplicates.

This pattern shows up constantly in interviews. Nail it, and you’re one step closer to that offer. Now go practice!


? Final Notes

Now go crush that interview! ?



ADVERTISEMENT