Open In App

Search in row wise sorted matrix

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a row-wise sorted matrix mat[][] and an integer x, the task is to check if is present in mat[][] or not. Note that there is no ordering among column elements.

Examples:

Input: x = 9, mat[][] = [[3, 4, 9],
[2, 5, 6],
[9, 25, 27]]
Output: true
Explanation: mat[0][2] is equal to 9.

Input: x = 56, mat[][] = [[19, 22, 27, 38, 55, 67]]
Output: false
Explanation: 56 is not present in mat[][].

[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. Please refer to Searching Algorithms for 2D Arrays (Matrix) to know more about the implementation.

[Expected Approach] Using Binary Search - O(n * log(m)) Time and O(1) Space

The idea is simple, we traverse through the matrix and apply binary search on each row to find the element.

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

#include <iostream>
#include <vector>

using namespace std;

bool search(vector<int> &arr, int x) {
	int lo = 0, hi = arr.size();
    while(lo <= hi) {
    	int mid = (lo + hi) / 2;
      
        // If x = mid, return true
        if(x == arr[mid]) 
            return true;
      
        // If x < arr[mid], search in left half
        if(x < arr[mid])
            hi = mid - 1;
       
        // If x > arr[mid], search in right half
        else
            lo = mid + 1;
    }
    return false;
}

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

int main() {
    vector<vector<int>> mat = {{3, 4, 9},
                               {2, 5, 6},
                               {9, 25, 27}};
    int x = 9;
    if(searchRowMatrix(mat, x)) 
        cout << "true";
    else 
        cout << "false";
    return 0;
}
Java
// Java program to search an element in row-wise
// sorted matrix 

import java.util.*;

class GfG {
    static boolean search(int[] arr, int x) {
        int lo = 0, hi = arr.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;

            // If x == mid, return true
            if (x == arr[mid])
                return true;

            // If x < arr[mid], search in the left half
            if (x < arr[mid])
                hi = mid - 1;

            // If x > arr[mid], search in the right half
            else
                lo = mid + 1;
        }
        return false;
    }

    static boolean searchRowMatrix(int[][] mat, int x) {
        int n = mat.length, m = mat[0].length;

        // Iterate over all the rows to find x
        for (int i = 0; i < n; i++) {

            // Perform binary search on the ith row
            if (search(mat[i], x))
                return true;
        }

        // If x was not found, return false
        return false;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {3, 4, 9},
            {2, 5, 6},
            {9, 25, 27}
        };
        int x = 9;

        if (searchRowMatrix(mat, x))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# Python program to search an element in row-wise
# sorted matrix 

def search(arr, x):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        
        # If x == mid, return true
        if x == arr[mid]:
            return True
        
        # If x < arr[mid], search in the left half
        if x < arr[mid]:
            hi = mid - 1
        
        # If x > arr[mid], search in the right half
        else:
            lo = mid + 1
    return False


def searchRowMatrix(mat, x):
    n, m = len(mat), len(mat[0])
    
    # Iterate over all the rows to find x
    for i in range(n):
        
        # Perform binary search on the ith row
        if search(mat[i], x):
            return True
    
    # If x was not found, return false
    return False

if __name__ == "__main__":
    mat = [[3, 4, 9],
           [2, 5, 6],
           [9, 25, 27]]
    x = 9
    if searchRowMatrix(mat, x):
        print("true")
    else:
        print("false")
C#
// C# program to search an element in row-wise
// sorted matrix 

using System;

class GfG {
    static bool Search(int[] arr, int x) {
        int lo = 0, hi = arr.Length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;

            // If x == mid, return true
            if (x == arr[mid])
                return true;

            // If x < arr[mid], search in the left half
            if (x < arr[mid])
                hi = mid - 1;

            // If x > arr[mid], search in the right half
            else
                lo = mid + 1;
        }
        return false;
    }

    // Function to search for element x in the matrix
    static bool SearchRowMatrix(int[][] mat, int x) {
        int n = mat.Length, m = mat[0].Length;

        // Iterate over all the rows to find x
        for (int i = 0; i < n; i++) {
            
            // Perform binary search on the ith row
            if (Search(mat[i], x))
                return true;
        }

        // If x was not found, return false
        return false;
    }

    static void Main() {
        int[][] mat = {
            new int[] { 3, 4, 9 },
            new int[] { 2, 5, 6 },
            new int[] { 9, 25, 27 }
        };
        int x = 9;

        if (SearchRowMatrix(mat, x))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// JavaScript program to search an element in row-wise
// sorted matrix 

function search(arr, x) {
    let lo = 0, hi = arr.length - 1;
    while (lo <= hi) {
        let mid = Math.floor((lo + hi) / 2);
      
        // If x == mid, return true
        if (x === arr[mid]) 
            return true;
      
        // If x < arr[mid], search in the left half
        if (x < arr[mid])
            hi = mid - 1;
       
        // If x > arr[mid], search in the right half
        else
            lo = mid + 1;
    }
    return false;
}

function searchRowMatrix(mat, x) {
    let n = mat.length, m = mat[0].length;
  
    // Iterate over all the rows to find x
    for (let i = 0; i < n; i++) {
        // Perform binary search on the ith row
        if (search(mat[i], x))
            return true;
    }
  
    // If x was not found, return false
    return false;
}

// Driver Code
let mat = [
    [3, 4, 9],
    [2, 5, 6],
    [9, 25, 27]
];
let x = 9;

if (searchRowMatrix(mat, x)) 
    console.log("true");
else 
    console.log("false");

Output
true

Time Complexity: O(n*logm), where n is the number of rows and m is the number of columns.
Auxiliary Space: O(1)


Next Article

Similar Reads