Given a 2D integer matrix mat[][] of size n x m, where every row and column is sorted in increasing order and a number x, return true if the element x is present in the matrix. Otherwise, return false.
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.
Table of Content
[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.
#include
#include
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;
}
#include
#include
bool matSearch(int n, int m,int mat[][m], int x) {
// 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() {
int n = 3, m = 3;
int mat[3][3] = {
{3, 30, 38},
{20, 52, 54},
{35, 60, 69}
};
int x = 35;
if (matSearch(n, m, mat, x))
printf("true");
else
printf("false");
return 0;
}
class GFG {
static boolean matSearch(int[][] mat, int x)
{
int n = mat.length, m = mat[0].length;
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;
}
public static void main(String[] args)
{
int[][] mat = { { 3, 30, 38 },
{ 20, 52, 54 },
{ 35, 60, 69 } };
int x = 35;
if (matSearch(mat, x))
System.out.println("true");
else
System.out.println("false");
}
}
def matSearch(mat, x):
n = len(mat)
m = len(mat[0])
for i in range(n):
for j in range(m):
if mat[i][j] == x:
return True
# If x was not found, return false
return False
if __name__ == "__main__":
mat = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
x = 35
if matSearch(mat, x):
print("true")
else:
print("false")
using System;
class GfG {
static bool matSearch(int[, ] mat, int x)
{
int n = mat.GetLength(0), m = mat.GetLength(1);
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;
}
static void Main()
{
int[, ] mat = { { 3, 30, 38 },
{ 20, 52, 54 },
{ 35, 60, 69 } };
int x = 35;
if (matSearch(mat, x))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
function matSearch(mat, x)
{
const n = mat.length, m = mat[0].length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (mat[i][j] === x)
return true;
}
}
// If x was not found, return false
return false;
}
// Driver Code
const mat =
[ [ 3, 30, 38 ], [ 20, 52, 54 ], [ 35, 60, 69 ] ];
const x = 35;
if (matSearch(mat, x))
console.log("true");
else
console.log("false");
Output
true
[Better Approach] Binary Search - O(n*logm) Time and O(1) Space
Instead of checking every element, use Binary Search on each row because the elements in every row are sorted.
For every row:
- Start with
lowat the first index andhighat the last index. - Find the middle index
mid. - If
mat[mid]is equal tox, returntrue. - If
mat[mid]is smaller thanx, continue searching in the right half. - Otherwise, continue searching in the left half.
- If
xis not found in the row, move to the next row. - If all rows are searched and
xis not found, returnfalse.
#include
#include
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;
// Element found
if (mat[mid] == target)
return true;
// Search in the right half
else if (target > mat[mid])
low = mid + 1;
// Search in the left half
else
high = mid - 1;
}
// Element not found
return false;
}
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))
// Element found in one of the rows
return true;
}
// Element not found in any row
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;
}
#include
#include
bool binarySearch(int mat[], int n, int target) {
int low = 0, high = n - 1;
// Standard binary search algorithm
while (low <= high) {
int mid = (low + high) / 2;
// Element found
if (mat[mid] == target)
return true;
// Search in the right half
else if (target > mat[mid])
low = mid + 1;
// Search in the left half
else
high = mid - 1;
}
// Element not found
return false;
}
bool matSearch(int n, int m, int mat[n][m], int x) {
// Iterate over each row and perform binary search
for (int i = 0; i < n; i++) {
if (binarySearch(mat[i], m, x))
// Element found in one of the rows
return true;
}
// Element not found in any row
return false;
}
int main() {
int n = 3, m = 3;
int mat[3][3] = {
{3, 30, 38},
{20, 52, 54},
{35, 60, 69}
};
int x = 35;
if (matSearch(n, m, mat, x))
printf("true");
else
printf("false");
return 0;
}
public class GFG {
public static boolean binarySearch(int[] mat,
int target)
{
int n = mat.length;
int low = 0, high = n - 1;
// Standard binary search algorithm
while (low <= high) {
int mid = (low + high) / 2;
// Element found
if (mat[mid] == target)
return true;
// Search in the right half
else if (target > mat[mid])
low = mid + 1;
// Search in the left half
else
high = mid - 1;
}
// Element not found
return false;
}
public static boolean matSearch(int[][] mat, int x)
{
int n = mat.length;
// Iterate over each row and perform binary search
for (int i = 0; i < n; i++) {
if (binarySearch(mat[i], x))
// Element found in one of the rows
return true;
}
// Element not found in any row
return false;
}
public static void main(String[] args)
{
int[][] mat = { { 3, 30, 38 },
{ 20, 52, 54 },
{ 35, 60, 69 } };
int x = 35;
if (matSearch(mat, x))
System.out.println("true");
else
System.out.println("false");
}
}
def binarySearch(mat, target):
n = len(mat)
low, high = 0, n - 1
# Standard binary search algorithm
while low <= high:
mid = (low + high) // 2
# Element found
if mat[mid] == target:
return True
# Search in the right half
elif target > mat[mid]:
low = mid + 1
# Search in the left half
else:
high = mid - 1
# Element not found
return False
def matSearch(mat, x):
n = len(mat)
# Iterate over each row and perform binary search
for i in range(n):
if binarySearch(mat[i], x):
# Element found in one of the rows
return True
# Element not found in any row
return False
if __name__ == "__main__":
mat = [
[3, 30, 38],
[20, 52, 54],
[35, 60, 69]
]
x = 35
if matSearch(mat, x):
print("true")
else:
print("false")
using System;
public class GFG {
public static bool binarySearch(int[,] mat, int row, int target)
{
int n = mat.GetLength(1);
int low = 0, high = n - 1;
// Standard binary search algorithm
while (low <= high) {
int mid = (low + high) / 2;
// Element found
if (mat[row, mid] == target)
return true;
// Search in the right half
else if (target > mat[row, mid])
low = mid + 1;
// Search in the left half
else
high = mid - 1;
}
// Element not found
return false;
}
public static bool matSearch(int[,] mat, int x)
{
int n = mat.GetLength(0);
// Iterate over each row and perform binary search
for (int i = 0; i < n; i++) {
if (binarySearch(mat, i, x))
// Element found in one of the rows
return true;
}
// Element not found in any row
return false;
}
public static void Main(string[] args)
{
int[,] mat = new int[,] { { 3, 30, 38 },
{ 20, 52, 54 },
{ 35, 60, 69 } };
int x = 35;
if (matSearch(mat, x))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
function binarySearch(mat, target)
{
let n = mat.length;
let low = 0, high = n - 1;
// Standard binary search algorithm
while (low <= high) {
let mid = Math.floor((low + high) / 2);
// Element found
if (mat[mid] === target)
return true;
// Search in the right half
else if (target > mat[mid])
low = mid + 1;
// Search in the left half
else
high = mid - 1;
}
// Element not found
return false;
}
function matSearch(mat, x)
{
let n = mat.length;
// Iterate over each row and perform binary search
for (let i = 0; i < n; i++) {
if (binarySearch(mat[i], x))
// Element found in one of the rows
return true;
}
// Element not found in any row
return false;
}
let mat = [ [ 3, 30, 38 ], [ 20, 52, 54 ], [ 35, 60, 69 ] ];
let x = 35;
if (matSearch(mat, x))
console.log("true");
else
console.log("false");
Output
true
[Expected Approach] Eliminating rows or columns - O(n + m) Time and O(1) Space
Since the matrix is sorted both row-wise and column-wise, the search space can be reduced after each comparison.
Start from the top-right corner and compare the current element with x.
- If x > mat[i][j], all elements to the left are smaller than x. So, the current row can be skipped, and move down to the next row.
- If x < mat[i][j], all elements below are greater than x. So, the current column can be skipped, and move left to the previous column.
- If x == mat[i][j], the element is found, so return true.
Continue this process until x is found or the search moves outside the matrix. If x is not found, return false.
#include
#include
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;
}
#include
#include
bool matSearch(int n, int m, int mat[n][m], int x) {
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 move to the next row
if (x > mat[i][j]) {
i++;
}
// If x < mat[i][j], then x will be smaller
// than all elements below mat[i][j]
// in column j, so move to the previous column
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() {
int n = 3, m = 3;
int mat[3][3] = {
{3, 30, 38},
{20, 52, 54},
{35, 60, 69}
};
int x = 35;
if (matSearch(n, m, mat, x))
printf("true");
else
printf("false");
return 0;
}
class GFG {
static boolean matSearch(int[][] mat, int x)
{
int n = mat.length, m = mat[0].length;
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;
}
public static void main(String[] args)
{
int[][] mat = { { 3, 30, 38 },
{ 20, 52, 54 },
{ 35, 60, 69 } };
int x = 35;
if (matSearch(mat, x))
System.out.println("true");
else
System.out.println("false");
}
}
def matSearch(mat, x):
n = len(mat)
m = len(mat[0])
i = 0
j = m - 1
while i < n and 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 += 1
# 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
elif x < mat[i][j]:
j -= 1
# If x = mat[i][j], return true
else:
return True
# If x was not found, return false
return False
if __name__ == "__main__":
mat = [
[3, 30, 38],
[20, 52, 54],
[35, 60, 69]
]
x = 35
if matSearch(mat, x):
print("true")
else:
print("false")
using System;
class GfG {
static bool matSearch(int[, ] mat, int x)
{
int n = mat.GetLength(0), m = mat.GetLength(1);
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;
}
static void Main()
{
int[, ] mat = { { 3, 30, 38 },
{ 20, 52, 54 },
{ 35, 60, 69 } };
int x = 35;
if (matSearch(mat, x))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
function matSearch(mat, x)
{
let n = mat.length, m = mat[0].length;
let 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;
}
// Driver Code
let mat = [ [ 3, 30, 38 ], [ 20, 52, 54 ], [ 35, 60, 69 ] ];
let x = 35;
if (matSearch(mat, x))
console.log("true");
else
console.log("false");
Output
true