Given an n x n matrix and an integer x, find the position of x in the matrix if it is present. Otherwise, print “Element not found”. Every row and column of the matrix is sorted in increasing order. The designed algorithm should have linear time complexity
Examples:
Input: mat[4][4] = { {10, 20, 30, 40}, x = 29
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}}
Output: Found at (2, 1)
Explanation: Element at (2,1) is 29
Input : mat[4][4] = { {10, 20, 30, 40}, x = 100
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
Output: Element not found
Explanation: Element 100 does not exist in the matrix
Naive approach: To solve the problem follow the below idea:
The simple idea is to traverse the array and search elements one by one
Follow the given steps to solve the problem:
- Run a nested loop, outer loop for the row, and inner loop for the column
- Check every element with x and if the element is found then print “element found”
- If the element is not found, then print “element not found”
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int search( int mat[4][4], int n, int x)
{
if (n == 0)
return -1;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++)
if (mat[i][j] == x) {
cout << "Element found at (" << i << ", "
<< j << ")\n" ;
return 1;
}
}
cout << "n Element not found" ;
return 0;
}
int main()
{
int mat[4][4] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
search(mat, 4, 29);
return 0;
}
|
C
#include <stdio.h>
int search( int mat[4][4], int n, int x)
{
if (n == 0)
return -1;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++)
if (mat[i][j] == x) {
printf ( "Element found at (%d, %d)\n" , i, j);
return 1;
}
}
printf ( "Element not found" );
return 0;
}
int main()
{
int mat[4][4] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
search(mat, 4, 29);
return 0;
}
|
Java
class GFG {
static int search( int [][] mat, int n, int x)
{
if (n == 0 )
return - 1 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n; j++)
if (mat[i][j] == x) {
System.out.print( "Element found at ("
+ i + ", " + j
+ ")\n" );
return 1 ;
}
}
System.out.print( " Element not found" );
return 0 ;
}
public static void main(String[] args)
{
int mat[][] = { { 10 , 20 , 30 , 40 },
{ 15 , 25 , 35 , 45 },
{ 27 , 29 , 37 , 48 },
{ 32 , 33 , 39 , 50 } };
search(mat, 4 , 29 );
}
}
|
Python3
def search(mat, n, x):
if (n = = 0 ):
return - 1
for i in range (n):
for j in range (n):
if (mat[i][j] = = x):
print ( "Element found at (" , i, "," , j, ")" )
return 1
print ( " Element not found" )
return 0
if __name__ = = "__main__" :
mat = [[ 10 , 20 , 30 , 40 ], [ 15 , 25 , 35 , 45 ],
[ 27 , 29 , 37 , 48 ], [ 32 , 33 , 39 , 50 ]]
search(mat, 4 , 29 )
|
C#
using System;
class GFG {
static int search( int [, ] mat, int n, int x)
{
if (n == 0)
return -1;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++)
if (mat[i, j] == x) {
Console.Write( "Element found at (" + i
+ ", " + j + ")\n" );
return 1;
}
}
Console.Write( " Element not found" );
return 0;
}
static public void Main()
{
int [, ] mat = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
search(mat, 4, 29);
}
}
|
Javascript
<script>
function search(mat,n,x) {
if (n == 0)
return -1;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++)
if (mat[i][j] == x) {
document.write( "Element found at ("
+ i + ", " + j
+ ")<br>" );
return 1;
}
}
document.write( " Element not found" );
return 0;
}
let mat = [[ 10, 20, 30, 40 ],
[15, 25, 35, 45] ,
[ 27, 29, 37, 48 ],
[ 32, 33, 39, 50 ]];
search(mat, 4, 29);
</script>
|
Output
Element found at (2, 1)
Time Complexity: O(N2)
Auxiliary Space: O(1), since no extra space has been taken
Note: A better solution is to use Divide and Conquer to find the element which has a time complexity of O(n1.58). Please refer here for details
Search in a row-wise and column-wise sorted matrix in linear time complexity:
The simple 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 three possible cases:-
- The given number is greater than the current number: This will ensure that all the elements in the current row are smaller than the given number as the pointer is already at the right-most elements and the row is sorted. Thus, the entire row gets eliminated and continues the search for the next row. Here, elimination means that a row needs not to be searched.
- The given number is smaller than the current number: This will ensure that all the elements in the current column are greater than the given number. Thus, the entire column gets eliminated and continues the search for the previous column, i.e. the column on the immediate left.
- The given number is equal to the current number: This will end the search.
Follow the given steps to solve the problem:
- Let the given element be x, create two variable i = 0, j = n-1 as index of row and column.
- Run a loop until i < n.
- Check if the current element is greater than x then decrease the count of j. Exclude the current column.
- Check if the current element is less than x then increase the count of i. Exclude the current row.
- If the element is equal, then print the position and end.
- Print the Element is not found
Thanks to devendraiiit for suggesting the approach below
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int search( int mat[4][4], int n, int x)
{
if (n == 0)
return -1;
int smallest = mat[0][0], largest = mat[n - 1][n - 1];
if (x < smallest || x > largest)
return -1;
int i = 0, j = n - 1;
while (i < n && j >= 0) {
if (mat[i][j] == x) {
cout << "Element found at " << i << ", " << j;
return 1;
}
if (mat[i][j] > x)
j--;
else
i++;
}
cout << "n Element not found" ;
return 0;
}
int main()
{
int mat[4][4] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
search(mat, 4, 29);
return 0;
}
|
C
#include <stdio.h>
int search( int mat[4][4], int n, int x)
{
if (n == 0)
return -1;
int smallest = mat[0][0], largest = mat[n - 1][n - 1];
if (x < smallest || x > largest)
return -1;
int i = 0, j = n - 1;
while (i < n && j >= 0) {
if (mat[i][j] == x) {
printf ( "Element found at %d, %d" , i, j);
return 1;
}
if (mat[i][j] > x)
j--;
else
i++;
}
printf ( "n Element not found" );
return 0;
}
int main()
{
int mat[4][4] = {
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 },
};
search(mat, 4, 29);
return 0;
}
|
Java
class GFG {
private static void search( int [][] mat, int n, int x)
{
int i = 0 , j = n - 1 ;
while (i < n && j >= 0 ) {
if (mat[i][j] == x) {
System.out.print( "Element found at " + i
+ " " + j);
return ;
}
if (mat[i][j] > x)
j--;
else
i++;
}
System.out.print( "n Element not found" );
return ;
}
public static void main(String[] args)
{
int mat[][] = { { 10 , 20 , 30 , 40 },
{ 15 , 25 , 35 , 45 },
{ 27 , 29 , 37 , 48 },
{ 32 , 33 , 39 , 50 } };
search(mat, 4 , 29 );
}
}
|
Python3
def search(mat, n, x):
i = 0
j = n - 1
while (i < n and j > = 0 ):
if (mat[i][j] = = x):
print ( "Element found at " , i, ", " , j)
return 1
if (mat[i][j] > x):
j - = 1
else :
i + = 1
print ( "Element not found" )
return 0
if __name__ = = "__main__" :
mat = [[ 10 , 20 , 30 , 40 ],
[ 15 , 25 , 35 , 45 ],
[ 27 , 29 , 37 , 48 ],
[ 32 , 33 , 39 , 50 ]]
search(mat, 4 , 29 )
|
C#
using System;
class GFG {
private static void search( int [, ] mat, int n, int x)
{
int i = 0, j = n - 1;
while (i < n && j >= 0) {
if (mat[i, j] == x) {
Console.Write( "Element found at " + i + ", "
+ j);
return ;
}
if (mat[i, j] > x)
j--;
else
i++;
}
Console.Write( "n Element not found" );
return ;
}
public static void Main()
{
int [, ] mat = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
search(mat, 4, 29);
}
}
|
Javascript
<script>
function search(mat,n,x){
let i = 0, j = n - 1;
while (i < n && j >= 0)
{
if (mat[i][j] == x)
{
document.write( "Element found at " +
i + " " + j);
return ;
}
if (mat[i][j] > x)
j--;
else
i++;
}
document.write( "n Element not found" );
return ;
}
let mat = [[10, 20, 30, 40 ],
[ 15, 25, 35, 45 ],
[ 27, 29, 37, 48 ],
[ 32, 33, 39, 50 ]];
search(mat, 4, 29);
</script>
|
PHP
<?php
function search(& $mat , $n , $x )
{
$i = 0;
$j = $n - 1;
while ( $i < $n && $j >= 0)
{
if ( $mat [ $i ][ $j ] == $x )
{
echo "Element found at " . $i .
", " . $j ;
return 1;
}
if ( $mat [ $i ][ $j ] > $x )
$j --;
else
$i ++;
}
echo "n Element not found" ;
return 0;
}
$mat = array ( array (10, 20, 30, 40),
array (15, 25, 35, 45),
array (27, 29, 37, 48),
array (32, 33, 39, 50));
search( $mat , 4, 29);
?>
|
Output
Element found at 2, 1
Time Complexity: O(N), Only one traversal is needed, i.e, i from 0 to n and j from n-1 to 0 with at most 2*N steps. The above approach will also work for the M x N matrix (not only for N x N). Complexity would be O(M + N)
Auxiliary Space: O(1), No extra space is required
Related Article: Search element in a sorted matrix
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Using Linear Search:
Approach:
In this approach, we traverse the matrix row by row and check each element until we find the target element.
Define a function search_element that takes a matrix mat and a target element x as input.
Traverse the matrix mat row by row using a nested loop.
For each element in the matrix, check if it is equal to the target element x.
If the target element is found, return its position as a string in the format “Found at (i, j)”, where i and j are the row and column indices of the element, respectively.
If the target element is not found, return the string “Element not found”.
C++
#include <iostream>
#include <vector>
using namespace std;
string search_element(vector<vector< int >> mat, int x) {
for ( int i = 0; i < mat.size(); i++) {
for ( int j = 0; j < mat[0].size(); j++) {
if (mat[i][j] == x) {
return "Found at (" + to_string(i) + ", " + to_string(j) + ")" ;
}
}
}
return "Element not found" ;
}
int main() {
vector<vector< int >> mat = {{10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
int x = 29;
cout << search_element(mat, x) << endl;
x = 100;
cout << search_element(mat, x) << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
class GFG {
public static String search_element(List<List<Integer>> mat, int x) {
for ( int i = 0 ; i < mat.size(); i++) {
for ( int j = 0 ; j < mat.get( 0 ).size(); j++) {
if (mat.get(i).get(j) == x) {
return "Found at (" + i + ", " + j + ")" ;
}
}
}
return "Element not found" ;
}
public static void main(String[] args) {
List<List<Integer>> mat = new ArrayList<>();
mat.add(List.of( 10 , 20 , 30 , 40 ));
mat.add(List.of( 15 , 25 , 35 , 45 ));
mat.add(List.of( 27 , 29 , 37 , 48 ));
mat.add(List.of( 32 , 33 , 39 , 50 ));
int x = 29 ;
System.out.println(search_element(mat, x));
x = 100 ;
System.out.println(search_element(mat, x));
}
}
|
Python3
def search_element(mat, x):
for i in range ( len (mat)):
for j in range ( len (mat[ 0 ])):
if mat[i][j] = = x:
return f "Found at ({i}, {j})"
return "Element not found"
mat = [
[ 10 , 20 , 30 , 40 ],
[ 15 , 25 , 35 , 45 ],
[ 27 , 29 , 37 , 48 ],
[ 32 , 33 , 39 , 50 ]
]
x = 29
print (search_element(mat, x))
x = 100
print (search_element(mat, x))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static string SearchElement(List<List< int >> mat, int x)
{
for ( int i = 0; i < mat.Count; i++)
{
for ( int j = 0; j < mat[0].Count; j++)
{
if (mat[i][j] == x)
{
return "Found at (" + i + ", " + j + ")" ;
}
}
}
return "Element not found" ;
}
static void Main( string [] args)
{
List<List< int >> mat = new List<List< int >>
{
new List< int > { 10, 20, 30, 40 },
new List< int > { 15, 25, 35, 45 },
new List< int > { 27, 29, 37, 48 },
new List< int > { 32, 33, 39, 50 }
};
int x = 29;
Console.WriteLine(SearchElement(mat, x));
x = 100;
Console.WriteLine(SearchElement(mat, x));
}
}
|
Javascript
function search_element(mat, x) {
for (let i = 0; i < mat.length; i++) {
for (let j = 0; j < mat[0].length; j++) {
if (mat[i][j] === x) {
return "Found at (" + i + ", " + j + ")" ;
}
}
}
return "Element not found" ;
}
const mat = [
[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]
];
let x = 29;
console.log(search_element(mat, x));
x = 100;
console.log(search_element(mat, x));
|
Output
Found at (2, 1)
Element not found
Time Complexity: O(n^2)
Space Complexity: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!