Given an n x n matrix and a number x, find the position of x in the matrix if it is present in it. Otherwise, print “Not Found”. In the given matrix, every row and column is sorted in increasing order. The designed algorithm should have linear time complexity.
Example:
Input: mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 29
Output: Found at (2, 1)
Explanation: Element at (2,1) is 29
Input : mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 100
Output : Element not found
Explanation: Element 100 is not found
Simple Solution
- Approach: The simple idea is to traverse the array and to search element one by one.
- Algorithm:
- Run a nested loop, outer loop for 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”.
- Implementation:
CPP14
#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;
}
|
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
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);
}
}
|
OutputElement found at (2, 1)
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.
Efficient Solution
- Approach: 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 element and the row is sorted. Thus, the entire row gets eliminated and continue the search on the next row. Here elimination means that 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 continue the search on the previous column i.e. the column at the immediate left.
- The given number is equal to the current number: This will end the search.
- Algorithm:
- 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 = 0
- 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.
- Thanks to devendraiiit for suggesting the below approach.
- Implementation:
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 << "n 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 ( "\n 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( "n 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 ( "n Found at " , i, ", " , j)
return 1
if (mat[i][j] > x ):
j - = 1
else :
i + = 1
print ( "Element not found" )
return 0
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( "n 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);
}
}
|
PHP
<?php
function search(& $mat , $n , $x )
{
$i = 0;
$j = $n - 1;
while ( $i < $n && $j >= 0)
{
if ( $mat [ $i ][ $j ] == $x )
{
echo "n 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);
?>
|
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 m x n matrix (not only for n x n). Complexity would be O(m + n).
Space Complexity: O(1).
No extra space is required.
https://youtu.be/_reu46LJtyk
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.