All Problems
Algorithm Visualizer

Search a 2D Matrix

O(log(m·n)) time · O(1) space · Single Binary Search (Flat Index)
Matrix Input
4
Ready — click Run or Step
Algorithm State
left (flat index)
right (flat index)
mid (flat index)
value at mid
row = mid / cols
col = mid % cols
Target
— result —
⏱ O(log(m·n)) time ◻ O(1) space
Solution Code
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {

        int rows  = matrix.size();
        int cols  = matrix[0].size();
        int left  = 0;
        int right = (rows * cols) - 1;

        // Treat the 2D matrix as a flat sorted array
        while (left <= right) {
            int mid   = left + (right - left) / 2;
            int row   = mid / cols;   // convert flat index → row
            int col   = mid % cols;   // convert flat index → col
            int value = matrix[row][col];

            if (value == target)
            {
                return true;   // found!
            }

            if (value < target)
            {
                left = mid + 1;   // target is to the right
            }

            else
            {
                right = mid - 1;   // target is to the left
            }
        }
        return false;   // not found
    }
};