LC74 Search in 2D matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.


We can search the matrix using binary search. Since the matrix is sorted in 2d. We can just first go to the middle. If the middle is too large, then we will only search the [0, middle – 1]…


We will not do 2d search. Instead we will treat this problem as 1D and convert the 1D ranking to 2D position.

bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.size() == 0)
            return false;
        if (matrix[0].size() == 0)
            return false;
        int colLen = matrix[0].size();
        int rowLen = matrix.size();
        int low = 0;
        int high = rowLen * colLen - 1;
        int mid = -1;
        int midX = -1;
        int midY = -1;
        while (low <= high){
            mid = low + (high - low) / 2;
            midY = mid / colLen;
            midX = mid % colLen;
            if (matrix[midY][midX] == target){
                return true;   

            if (matrix[midY][midX] > target){
                high = mid - 1;
                low = mid + 1;
        return false;

Take away

When you see efficient algorithm for search, and the input is in any kind of sorted form(2d, 3d… what ever) think binary search

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see