</>

74. Search a 2D Matrix

Medium NeetCode 150
Binary Search Time O(log m + log n) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Binary Search
Time
O(log m + log n)
Space
O(1)

Standard Solution (C++)

SummaryGiven a sorted integer matrix where each row is sorted left-to-right and the first element of each row is greater than the last element of the previous row, determine whether a target value exists in the matrix.

Approach
  • Treat the entire m×n matrix as a single sorted array of length mn and run one binary search over virtual indices 0..mn-1.
  • Convert a virtual mid index to a 2-D coordinate with row = mid / n and col = mid % n, then compare matrix[row][col] to target.
  • This works because the row-major layout of a matrix that satisfies the two sorted-order constraints is itself a fully sorted sequence.
  • One pass gives O(log(m·n)) = O(log m + log n) time with O(1) extra space.
#include <vector>
using namespace std;

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();
        int n = matrix[0].size();

        // Treat the matrix as a flat sorted array of length m*n.
        int lo = 0, hi = m * n - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;      // avoids overflow
            int val = matrix[mid / n][mid % n]; // map flat index -> 2-D cell

            if (val == target) return true;
            if (val < target)  lo = mid + 1;
            else               hi = mid - 1;
        }

        return false;
    }
};
Time O(log(m * n)) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m=matrix.size();
        int n=matrix[0].size();
        
        // do 2 binary searchs
        int top=0;
        int down=m-1;
        
        int targetRow=-1;
        while(top<=down){
            int mid=(top+down)/2;
            int val=matrix[mid][0];
            if(val==target){
                return true;
            }
            else if(val<target){
                targetRow=mid; // temporarily keep it
                top=mid+1;
            }
            else{
                down=mid-1;
            }
        }

        if(targetRow==-1){
            return false;
        }

        int left=0;
        int right=n-1;

        while(left<=right){
            int mid=(left+right)/2;
            int val=matrix[targetRow][mid];
            if(val==target){
                return true;
            }
            if(val<target){
                left=mid+1;
            }
            else{
                right=mid-1;
            }
        }

        return false;
    }
};

// Time Complexity: O(log m + log n)=O(log mn)
// Space Complexity: O(1)
Time O(log m + log n) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern