Bird
Raised Fist0
DSA Cprogramming

Search in 2D Matrix in DSA C

Choose your learning style10 modes available
Mental Model
We look for a number in a grid where each row and column is sorted, moving step by step to find it quickly.
Analogy: Imagine searching for a name in a phone book arranged by first and last names. You start at the top-right corner and decide to go left or down based on comparisons, skipping many entries at once.
Matrix:
1  4  7  11
2  5  8  12
3  6  9  16
10 13 14 17
Start at top-right (↑):
1  4  7  [11↑]
2  5  8  12
3  6  9  16
10 13 14 17
Dry Run Walkthrough
Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 5
Goal: Find if 5 exists in the matrix efficiently
Step 1: Start at top-right element 11
1  4  7  [11↑]
2  5  8  12
3  6  9  16
10 13 14 17
Why: We start here because it helps decide whether to go left or down
Step 2: Compare 11 with 5; 11 > 5, move left to 7
1  4  [7↑] 11
2  5  8  12
3  6  9  16
10 13 14 17
Why: Since 11 is bigger than 5, smaller numbers are to the left
Step 3: Compare 7 with 5; 7 > 5, move left to 4
1  [4↑] 7  11
2  5  8  12
3  6  9  16
10 13 14 17
Why: 7 is bigger than 5, so move left again
Step 4: Compare 4 with 5; 4 < 5, move down to 5
1  [4] 7  11
2  [5↑] 8  12
3  6  9  16
10 13 14 17
Why: 4 is smaller than 5, so move down to find bigger numbers
Step 5: Compare 5 with 5; found target
1  4  7  11
2  [5↑] 8  12
3  6  9  16
10 13 14 17
Why: We found the target number
Result:
Target 5 found at position (1,1)
Annotated Code
DSA C
#include <stdio.h>
#include <stdbool.h>

bool searchMatrix(int matrix[][4], int rows, int cols, int target) {
    int r = 0;
    int c = cols - 1;
    while (r < rows && c >= 0) {
        if (matrix[r][c] == target) {
            return true;
        } else if (matrix[r][c] > target) {
            c--;
        } else {
            r++;
        }
    }
    return false;
}

int main() {
    int matrix[4][4] = {
        {1, 4, 7, 11},
        {2, 5, 8, 12},
        {3, 6, 9, 16},
        {10, 13, 14, 17}
    };
    int target = 5;
    if (searchMatrix(matrix, 4, 4, target)) {
        printf("Target %d found in matrix\n", target);
    } else {
        printf("Target %d not found in matrix\n", target);
    }
    return 0;
}
while (r < rows && c >= 0) {
loop while inside matrix bounds
if (matrix[r][c] == target) {
check if current element matches target
c--;
move left if current element is bigger than target
r++;
move down if current element is smaller than target
OutputSuccess
Target 5 found in matrix
Complexity Analysis
Time: O(m + n) because we move at most m times down and n times left in the matrix
Space: O(1) because we use only a few variables, no extra space proportional to input
vs Alternative: Compared to searching every element O(m*n), this method is much faster by skipping many elements
Edge Cases
target smaller than smallest element
returns false quickly by moving left out of bounds
DSA C
while (r < rows && c >= 0) {
target larger than largest element
returns false quickly by moving down out of bounds
DSA C
while (r < rows && c >= 0) {
empty matrix (0 rows or 0 cols)
function returns false immediately as loop condition fails
DSA C
while (r < rows && c >= 0) {
When to Use This Pattern
When you see a sorted 2D matrix and need to find a value quickly, use the top-right corner search pattern to eliminate rows or columns stepwise.
Common Mistakes
Mistake: Starting search from top-left or bottom-left corner without adjusting logic
Fix: Always start from top-right corner to decide moving left or down correctly
Mistake: Not checking matrix bounds in the loop condition
Fix: Use while (r < rows && c >= 0) to avoid out-of-bound errors
Summary
Searches a sorted 2D matrix for a target by moving left or down from the top-right corner.
Use when matrix rows and columns are sorted and you want efficient search.
Start at top-right and move left if current is too big, down if too small, to skip many elements.

Practice

(1/5)
1. What is the main idea behind searching a target value in a 2D matrix where each row is sorted and the first integer of each row is greater than the last integer of the previous row?
easy
A. Start from bottom-left corner and move up or right
B. Search each row linearly until the target is found
C. Use a hash map to store all elements for quick lookup
D. Treat the 2D matrix as a sorted 1D array and apply binary search

Solution

  1. Step 1: Understand matrix sorting property

    Each row is sorted and the first element of a row is greater than the last element of the previous row, so the entire matrix can be seen as a sorted list.
  2. Step 2: Apply binary search on the matrix

    By treating the matrix as a single sorted array, binary search can be used efficiently to find the target.
  3. Final Answer:

    Treat the 2D matrix as a sorted 1D array and apply binary search -> Option D
  4. Quick Check:

    Matrix sorted row-wise = binary search [OK]
Hint: Think of the matrix as one sorted list for binary search [OK]
Common Mistakes:
  • Searching each row linearly wastes time
  • Using hash map wastes extra space
  • Starting from bottom-left only works if columns are sorted
2. Which of the following C code snippets correctly calculates the middle element index when performing binary search on a 2D matrix with rows and columns?
easy
A. int mid = (low + high) / 2; int row = mid % rows; int col = mid / cols;
B. int mid = (low + high) / 2; int row = mid / cols; int col = mid % cols;
C. int mid = (low + high) >> 1; int row = mid % cols; int col = mid / rows;
D. int mid = (low + high) / 2; int row = mid / rows; int col = mid % rows;

Solution

  1. Step 1: Calculate mid index in 1D

    mid = (low + high) / 2 correctly finds the middle index between low and high.
  2. Step 2: Convert mid to 2D indices

    Row is mid divided by number of columns (mid / cols), column is mid modulo number of columns (mid % cols).
  3. Final Answer:

    int mid = (low + high) / 2; int row = mid / cols; int col = mid % cols; -> Option B
  4. Quick Check:

    Row = mid/cols, Col = mid%cols [OK]
Hint: Divide mid by cols for row, modulo cols for column [OK]
Common Mistakes:
  • Swapping rows and columns in calculation
  • Using rows instead of cols for division/modulo
  • Using bit shift incorrectly for mid
3. What will be the output of the following C code snippet searching for target 5 in the matrix?
int matrix[3][4] = {
  {1, 3, 5, 7},
  {10, 11, 16, 20},
  {23, 30, 34, 60}
};
int target = 5;
int rows = 3, cols = 4;
int low = 0, high = rows * cols - 1;
int found = 0;
while (low <= high) {
  int mid = (low + high) / 2;
  int r = mid / cols;
  int c = mid % cols;
  if (matrix[r][c] == target) {
    found = 1;
    break;
  } else if (matrix[r][c] < target) {
    low = mid + 1;
  } else {
    high = mid - 1;
  }
}
printf("%d\n", found);
medium
A. 1
B. 0
C. 5
D. Compilation error

Solution

  1. Step 1: Perform binary search on matrix

    The code treats the matrix as a sorted 1D array and searches for target 5 using binary search.
  2. Step 2: Check if target 5 exists

    5 is present at matrix[0][2], so found will be set to 1 and loop breaks.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Target found = 1 [OK]
Hint: Binary search returns 1 if target found, else 0 [OK]
Common Mistakes:
  • Confusing indices calculation for row and column
  • Not updating low and high correctly
  • Printing target value instead of found flag
4. Identify the bug in the following C code snippet that searches for a target in a 2D matrix and suggest the fix:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
int target = 4;
int rows = 2, cols = 3;
int low = 0, high = rows * cols - 1;
int found = 0;
while (low < high) {
  int mid = (low + high) / 2;
  int r = mid / cols;
  int c = mid % cols;
  if (matrix[r][c] == target) {
    found = 1;
    break;
  } else if (matrix[r][c] < target) {
    low = mid + 1;
  } else {
    high = mid - 1;
  }
}
printf("%d\n", found);
medium
A. Change mid calculation to (low + high + 1) / 2
B. Swap row and column calculation
C. Change while condition to low <= high
D. Initialize found to -1 instead of 0

Solution

  1. Step 1: Analyze loop condition

    The loop uses while (low < high), which misses the case when low == high, possibly skipping the last element.
  2. Step 2: Fix loop condition

    Changing to while (low <= high) ensures all elements are checked, including when low equals high.
  3. Final Answer:

    Change while condition to low <= high -> Option C
  4. Quick Check:

    Loop must check low == high [OK]
Hint: Use while(low <= high) for complete binary search [OK]
Common Mistakes:
  • Using < instead of <= in loop condition
  • Incorrect mid calculation causing infinite loop
  • Swapping row and column indices
5. Given a 2D matrix where each row and each column is sorted in ascending order, but the first integer of each row is NOT necessarily greater than the last integer of the previous row, which approach is best to search for a target value efficiently?
hard
A. Start from top-right corner and move left or down
B. Search each row using binary search separately
C. Use binary search treating matrix as 1D sorted array
D. Use linear search over all elements

Solution

  1. Step 1: Understand matrix property

    Rows are sorted but no guarantee about relation between rows, so matrix is not fully sorted as 1D array.
  2. Step 2: Choose search method

    Starting from top-right corner, move left if current > target, move down if current < target, efficiently narrows search.
  3. Final Answer:

    Start from top-right corner and move left or down -> Option A
  4. Quick Check:

    Partial row sorting = stair-step search [OK]
Hint: Use stair-step search from top-right for partially sorted matrix [OK]
Common Mistakes:
  • Applying full binary search on unsorted matrix
  • Searching each row linearly wasting time
  • Using hash map wasting extra space
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard