Open In App

Search in a row wise and column wise sorted matrix

Last Updated : 22 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a matrix mat[][] and an integer x, the task is to check if x is present in mat[][] or not. Every row and column of the matrix is sorted in increasing order.

Examples: 

Input: x = 62, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: false
Explanation: 62 is not present in the matrix.

Input: x = 55, mat[][] = [[18, 21, 27],
[38, 55, 67]]
Output: true
Explanation: mat[1][1] is equal to 55.

Input: x = 35, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: true
Explanation: mat[2][0] is equal to 35.

[Naive Approach] Comparing with all elements – O(n*m) Time and O(1) Space

The simple idea is to traverse the complete matrix and search for the target element. If the target element is found, return true. Otherwise, return false.

C++
// C++ program to search an element in row-wise
// and column-wise sorted matrix 

#include <iostream>
#include <vector>

using namespace std;

bool matSearch(vector<vector<int>> &mat, int x) {
    int n = mat.size(), m = mat[0].size();
  
    // Iterate over all the elements to find x
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            if(mat[i][j] == x)
                return true;
        }
    }
  
    // If x was not found, return false
    return false;
}

int main() {
    vector<vector<int>> mat = {{3, 30, 38},
                               {20, 52, 54},
                               {35, 60, 69}};
    int x = 35;
    if(matSearch(mat, x)) 
        cout << "true";
    else 
        cout << "false";
    return 0;
}
Java Python C# JavaScript

Output
true

[Better Approach] Binary Search – O(n*logm) Time and O(1) Space:

To optimize the above approach we are going to use the Binary Search algorithm.
The problem specifies that each row in the given matrix is sorted in ascending order. Instead of searching each column sequentially, we can efficiently apply Binary Search on each row to determine if the target is present.

C++
// C++ program to search an element in row-wise
// and column-wise sorted matrix

#include <iostream>
#include <vector>

using namespace std;

bool binarySearch(vector<int> &mat, int target) {
    int n = mat.size();
    int low = 0, high = n - 1;

    // Standard binary search algorithm
    while (low <= high) {
        int mid = (low + high) / 2;
        
        if (mat[mid] == target) 
            return true;  // Element found
        else if (target > mat[mid]) 
            low = mid + 1; // Search in the right half
        else 
            high = mid - 1; // Search in the left half
    }
    return false;  // Element not found
}

bool matSearch(vector<vector<int>> &mat, int x) {
    int n = mat.size();

    // Iterate over each row and perform binary search
    for (int i = 0; i < n; i++) {
        if (binarySearch(mat[i], x)) 
            return true;  // Element found in one of the rows
    }
    
    return false;  // Element not found in any row
}

int main() {
    vector<vector<int>> mat = {{3, 30, 38},
                               {20, 52, 54},
                               {35, 60, 69}};
    int x = 35;
    if(matSearch(mat, x)) 
        cout << "true";
    else 
        cout << "false";
    return 0;
}
Java Python C# JavaScript

Output
true


[Expected Approach] Eliminating rows or columns – O(n + m) Time and O(1) Space:

The idea is to remove a row or column in each comparison until an element is found. Start searching from the top-right corner of the matrix. There are 3 possible cases:

  1. x is greater than the current element: This ensures that all the elements in the current row are smaller than the given number as the pointer is already at the right-most element and the row is sorted. Thus, the entire row gets eliminated and continues the search from the next row.
  2. x is smaller than the current element: This ensures that all the elements in the current column are greater than the given number. Thus, the entire column gets eliminated and continues the search from the previous column, i.e. the column on the immediate left.
  3. The given number is equal to the current number: This will end the search.

Illustration:


C++
// C++ program to search an element in row-wise
// and column-wise sorted matrix 

#include <iostream>
#include <vector>

using namespace std;

bool matSearch(vector<vector<int>> &mat, int x) {
    int n = mat.size(), m = mat[0].size();
    int i = 0, j = m - 1;
  
    while(i < n && j >= 0) {
      
        // If x > mat[i][j], then x will be greater
        // than all elements to the left of 
        // mat[i][j] in row i, so increment i
        if(x > mat[i][j]) {
            i++;
        }
      
        // If x < mat[i][j], then x will be smaller
        // than all elements to the bottom of
        // mat[i][j] in column j, so decrement j
        else if(x < mat[i][j]) {
            j--;
        }
      
        // If x = mat[i][j], return true
        else {
            return true;
        }
    }
  
    // If x was not found, return false
    return false;
}

int main() {
    vector<vector<int>> mat = {{3, 30, 38},
                               {20, 52, 54},
                               {35, 60, 69}};
    int x = 35;
    if(matSearch(mat, x)) 
        cout << "true";
    else 
        cout << "false";
    return 0;
}
Java Python C# JavaScript

Output
true


Related Article: Search element in a sorted matrix



Similar Reads

three90RightbarBannerImg