Search in row wise sorted matrix
Last Updated :
19 Dec, 2024
Given a row-wise sorted matrix mat[][] and an integer x, the task is to check if x 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");
Time Complexity: O(n*logm), where n is the number of rows and m is the number of columns.
Auxiliary Space: O(1)
Similar Reads
Search in a row wise and column wise sorted matrix 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: falseExplanation: 62 is not present in the matrix.Inpu
14 min read
Find median in row wise sorted matrix Given a row-wise sorted matrix mat[][] of order n * m, where the number of rows and columns are always odd. The task is to find the median of the matrix.Note: Median is the middle number in a sorted ascending or descending list of numbers. In case of an even number of elements return the left median
15+ min read
Search element in a sorted matrix Given a sorted matrix mat[][] of size nxm and an element x, the task is to find if x is present in the matrix or not. Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row i, where 1 <= i <= n-1, the first element of row i is greater than or equal
13 min read
Search in a sorted 2D matrix (Stored in row major order) Given an integer 'K' and a row-wise sorted 2-D Matrix i.e. the 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.The task is to find whether the integer 'K' is present in the matr
1 min read
Search element in a Spirally sorted Matrix Given a spirally sorted matrix with N Ã N elements and an integer X, the task is to find the position of this given integer in the matrix if it exists, else print -1. Note that all the matrix elements are distinct. Examples: Input: arr[] = { {1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8,
15+ min read
Sort the matrix row-wise and column-wise Given a n x n matrix. The problem is to sort the matrix row-wise and column wise. Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 1
9 min read
Count all sorted rows in a matrix Given a matrix of m*n size, the task is to count all the rows in a matrix that are sorted either in strictly increasing order or in strictly decreasing order?Examples : Input : m = 4, n = 5 mat[m][n] = 1 2 3 4 5 4 3 1 2 6 8 7 6 5 4 5 7 8 9 10Output: 3The idea is simple and involves two traversals of
10 min read
Search in matrix where only individual columns are sorted Given an n * m semi-sorted 2D matrix, mat[][] where each column is individually sorted in ascending order but the rows are not sorted, and a target element x. The task is to find the position (row and column index) of x in the matrix. If the element is not found, return -1.Examples: Input: mat[][] =
7 min read
How to do binary search step by step? Binary search is an efficient search algorithm that works on sorted arrays or lists. It repeatedly divides the search space in half until the target element is found or the search space is exhausted. Step-by-Step Guide to Perform Binary Search:Step 1: Initialize Variableslow: Set this variable to 0,
3 min read
Sort the given Matrix In-Place Given a matrix of m rows and n columns, the task is to sort the matrix in the strict order that is every row is sorted in increasing order and the first element of every row is greater than the first element of the previous row.Input : mat[][] = { {5, 4, 7}, {1, 3, 8}, {2, 9, 6} }Output : 1 2 3 4 5
9 min read