Bird
Raised Fist0
DSA C++programming~20 mins

Search in 2D Matrix in DSA C++ - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
2D Matrix Search Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of search in sorted 2D matrix
What is the output of the following C++ code that searches for the target 5 in a sorted 2D matrix?
DSA C++
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int r = 0, 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() {
    vector<vector<int>> matrix = {
        {1, 4, 7, 11},
        {2, 5, 8, 12},
        {3, 6, 9, 16},
        {10, 13, 14, 17}
    };
    bool found = searchMatrix(matrix, 5);
    cout << (found ? "Found" : "Not Found") << endl;
    return 0;
}
ARuntime Error
BFound
CCompilation Error
DNot Found
Attempts:
2 left
💡 Hint
Start searching from the top-right corner and move left or down based on comparison.
❓ Predict Output
intermediate
2:00remaining
Output when target is absent in 2D matrix
What will be the output of this C++ code searching for target 15 in the given sorted 2D matrix?
DSA C++
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int r = 0, 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() {
    vector<vector<int>> matrix = {
        {1, 4, 7, 11},
        {2, 5, 8, 12},
        {3, 6, 9, 16},
        {10, 13, 14, 17}
    };
    bool found = searchMatrix(matrix, 15);
    cout << (found ? "Found" : "Not Found") << endl;
    return 0;
}
ANot Found
BRuntime Error
CCompilation Error
DFound
Attempts:
2 left
💡 Hint
Trace the search path carefully; 15 is not in the matrix.
🔧 Debug
advanced
2:00remaining
Identify the error in 2D matrix search code
What error will this C++ code produce when searching for target 3 in a 2D matrix?
DSA C++
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int r = 0, c = cols;
    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() {
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    bool found = searchMatrix(matrix, 3);
    cout << (found ? "Found" : "Not Found") << endl;
    return 0;
}
ACompilation Error
BOutput: Not Found
COutput: Found
DRuntime Error: out_of_range
Attempts:
2 left
💡 Hint
Check the initial value of column index c.
❓ Predict Output
advanced
2:00remaining
Output of binary search on flattened 2D matrix
What is the output of this C++ code that uses binary search on a flattened 2D matrix to find target 8?
DSA C++
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int left = 0, right = rows * cols - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        int mid_value = matrix[mid / cols][mid % cols];
        if (mid_value == target) return true;
        else if (mid_value < target) left = mid + 1;
        else right = mid - 1;
    }
    return false;
}

int main() {
    vector<vector<int>> matrix = {
        {1, 3, 5, 7},
        {10, 11, 16, 20},
        {23, 30, 34, 50}
    };
    bool found = searchMatrix(matrix, 8);
    cout << (found ? "Found" : "Not Found") << endl;
    return 0;
}
AFound
BCompilation Error
CNot Found
DRuntime Error
Attempts:
2 left
💡 Hint
8 is not in the matrix; binary search will fail to find it.
🧠 Conceptual
expert
2:00remaining
Time complexity of search in sorted 2D matrix
Given a sorted 2D matrix where each row and column is sorted ascending, what is the time complexity of the search algorithm that starts from the top-right corner and moves left or down?
AO(m + n), where m is number of rows and n is number of columns
BO(m * n), where m is number of rows and n is number of columns
CO(log(m * n)), binary search on flattened matrix
DO(log m + log n), binary search on rows and columns separately
Attempts:
2 left
💡 Hint
Each step moves either one row down or one column left, never revisiting elements.

Practice

(1/5)
1. What is the main idea behind searching in a 2D matrix where each row and column is sorted in ascending order?
easy
A. Use binary search on each row independently
B. Start from the top-right corner and move left or down based on comparison
C. Search each element row by row until the target is found
D. Start from the bottom-left corner and move right or up based on comparison

Solution

  1. Step 1: Understand matrix properties

    Each row and column is sorted ascending, so top-right element is a good start to decide direction.
  2. Step 2: Use top-right corner to guide search

    If target is less than current element, move left; if greater, move down.
  3. Final Answer:

    Start from the top-right corner and move left or down based on comparison -> Option B
  4. Quick Check:

    Top-right corner search = Start from the top-right corner and move left or down based on comparison [OK]
Hint: Start at top-right, move left/down based on target comparison [OK]
Common Mistakes:
  • Starting from bottom-left without adjusting moves
  • Searching all elements without using sorting
  • Using binary search on unsorted columns
2. Which of the following C++ code snippets correctly initializes a 2D vector matrix with 3 rows and 4 columns filled with zeros?
easy
A. std::vector matrix(4, std::vector<int>(3, 0));
B. std::vector<int> matrix(3, std::vector<int>(4, 0));
C. std::vector matrix(3, std::vector<int>(4, 0));
D. std::vector matrix(3, 4, 0);

Solution

  1. Step 1: Understand vector initialization syntax

    To create a 2D vector with 3 rows and 4 columns, use vector of vectors with inner vector size 4.
  2. Step 2: Check each option

    std::vector matrix(3, std::vector<int>(4, 0)); correctly uses vector with 3 rows and inner vector of size 4 filled with 0.
  3. Final Answer:

    std::vector matrix(3, std::vector<int>(4, 0)); -> Option C
  4. Quick Check:

    Correct 2D vector init = std::vector matrix(3, std::vector<int>(4, 0)); [OK]
Hint: Use vector(rows, vector<int>(cols, val)) [OK]
Common Mistakes:
  • Using wrong vector type for inner vector
  • Swapping rows and columns sizes
  • Trying to pass three arguments to vector constructor
3. What will be the output of the following C++ code snippet?
std::vector matrix = {
  {1, 4, 7, 11},
  {2, 5, 8, 12},
  {3, 6, 9, 16},
  {10, 13, 14, 17}
};
int target = 5;
int row = 0, col = 3;
bool found = false;
while (row < 4 && col >= 0) {
  if (matrix[row][col] == target) {
    found = true;
    break;
  } else if (matrix[row][col] > target) {
    col--;
  } else {
    row++;
  }
}
std::cout << (found ? "Found" : "Not Found") << std::endl;
medium
A. Found
B. Not Found
C. Compilation Error
D. Runtime Error

Solution

  1. Step 1: Trace the search starting at matrix[0][3]

    matrix[0][3] = 11, target=5, 11 > 5 so col-- to 2.
  2. Step 2: Continue search

    matrix[0][2] = 7, 7 > 5 so col-- to 1; matrix[0][1] = 4, 4 < 5 so row++ to 1; matrix[1][1] = 5 equals target, found = true.
  3. Final Answer:

    Found -> Option A
  4. Quick Check:

    Search finds 5 at (1,1) = Found [OK]
Hint: Start top-right, move left if bigger, down if smaller [OK]
Common Mistakes:
  • Not updating row and col correctly
  • Confusing comparison operators
  • Assuming target not found without full search
4. Identify the bug in the following C++ code that searches for a target in a sorted 2D matrix:
bool searchMatrix(std::vector& matrix, int target) {
  int row = 0, col = matrix[0].size() - 1;
  while (row <= matrix.size() && col >= 0) {
    if (matrix[row][col] == target) return true;
    else if (matrix[row][col] > target) col--;
    else row++;
  }
  return false;
}
medium
A. The while loop condition should use < instead of <= for row
B. The initial column index is incorrect
C. The function should return false inside the loop
D. The matrix should be passed by value, not reference

Solution

  1. Step 1: Analyze loop boundary for row index

    matrix.size() gives number of rows; valid row indices are 0 to size()-1, so row < size() is correct.
  2. Step 2: Identify off-by-one error

    Using row <= matrix.size() allows row to equal size(), causing out-of-bounds access.
  3. Final Answer:

    The while loop condition should use < instead of <= for row -> Option A
  4. Quick Check:

    Row index must be less than size() [OK]
Hint: Use < size() for indices, not <= size() [OK]
Common Mistakes:
  • Using <= causing out-of-bounds errors
  • Incorrect initial column index
  • Returning false too early inside loop
5. Given a 2D matrix where each row and column is sorted ascending, write a function to count how many elements are less than or equal to a target value. Which approach is most efficient?
hard
A. Flatten matrix and sort, then count using binary search (O(m*n log(m*n)))
B. Use binary search on each row to find count per row (O(m*log n))
C. Traverse each element and count if <= target (O(m*n))
D. Start from bottom-left and move up or right to count (O(m+n))

Solution

  1. Step 1: Understand matrix sorted property

    Rows and columns sorted ascending allows efficient traversal from bottom-left.
  2. Step 2: Use bottom-left traversal to count elements

    Start at bottom-left; if element <= target, all elements above in that column are <= target, move right and add count; else move up.
  3. Step 3: Compare efficiency

    This approach visits at most m+n elements, better than binary search on each row or full traversal.
  4. Final Answer:

    Start from bottom-left and move up or right to count (O(m+n)) -> Option D
  5. Quick Check:

    Bottom-left traversal counts in O(m+n) [OK]
Hint: Count using bottom-left traversal for O(m+n) time [OK]
Common Mistakes:
  • Using full traversal causing O(m*n) time
  • Applying binary search on unsorted columns
  • Flattening matrix unnecessarily increasing complexity
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