Bird
Raised Fist0
DSA Cprogramming~10 mins

Search in 2D Matrix in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - Search in 2D Matrix
Start at top-right corner
↓
Compare target with current element
↓
Move left
↓
Check if inside matrix bounds
Yes↓
Repeat comparison
No↓
Not found
Start from the top-right element, compare with target, move left if target is smaller, move down if target is larger, repeat until found or out of bounds.
Execution Sample
DSA C
int searchMatrix(int matrix[][4], int rows, int cols, int target) {
    int r = 0, c = cols - 1;
    while (r < rows && c >= 0) {
        if (matrix[r][c] == target) return 1;
        else if (matrix[r][c] > target) c--;
        else r++;
    }
    return 0;
}
Search target in a sorted 2D matrix by starting at top-right and moving left or down.
Execution Table
StepOperationCurrent Position (r,c)Current ElementComparisonActionVisual State
1Start(0,3)1515 > 5Move left (c--)[[1,3,5,15],[2,6,9,20],[3,7,11,30],[10,12,16,40]]
2Compare(0,2)55 == 5Found target[[1,3,5,15],[2,6,9,20],[3,7,11,30],[10,12,16,40]]
3Exit---Return 1 (found)[[1,3,5,15],[2,6,9,20],[3,7,11,30],[10,12,16,40]]
💡 Target found at position (0,2), search ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
r0000
c3222
Current Element15555
Key Moments - 3 Insights
Why do we start searching from the top-right corner?
Because from top-right, moving left decreases the element value and moving down increases it, allowing efficient elimination of rows or columns as shown in steps 1 and 2 in the execution_table.
What happens if the current element is greater than the target?
We move left (decrease column index) to find smaller elements, as seen in step 1 where 15 > 5 leads to c--.
Why do we stop when indices go out of matrix bounds?
Because it means the target is not present in the matrix, as the search space is exhausted without a match, shown by the exit condition in the code and exit_note.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'c' after step 1?
A3
B2
C1
D0
💡 Hint
Check the 'Current Position (r,c)' column in step 2 of execution_table.
At which step does the algorithm find the target?
AStep 2
BStep 3
CStep 1
DIt never finds the target
💡 Hint
Look at the 'Action' column where it says 'Found target'.
If the target was 17, what would be the next action after starting at (0,3)?
AMove left (c--)
BReturn found
CMove down (r++)
DStop search
💡 Hint
Compare 15 and 17 in step 1 to decide movement direction.
Concept Snapshot
Search in 2D Matrix:
- Start at top-right element (row=0, col=cols-1)
- Compare target with current element
- If equal, return found
- If current > target, move left (col--)
- If current < target, move down (row++)
- Stop when out of bounds or found
Full Transcript
This concept shows how to search a target value in a 2D matrix sorted row-wise and column-wise. We start from the top-right corner element. If this element equals the target, we are done. If it is greater than the target, we move left to smaller elements. If it is smaller, we move down to larger elements. We repeat this until we find the target or go out of matrix bounds, which means the target is not present. The execution table traces each step with current position, element, comparison, and action. Variable tracker shows how row and column indices change. Key moments clarify why we start at top-right and how movement decisions are made. The visual quiz tests understanding of these steps. This method efficiently narrows down the search space in O(rows + cols) time.

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