Skip to content
Related Articles

Related Articles

Search in a row wise and column wise sorted matrix

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 19 Sep, 2022
Improve Article
Save Article

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++




// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <bits/stdc++.h>
 
using namespace std;
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
    if (n == 0)
        return -1;
 
    // traverse through the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            // if the element is found
            if (mat[i][j] == x) {
                cout << "Element found at (" << i << ", "
                     << j << ")\n";
                return 1;
            }
    }
 
    cout << "n Element not found";
    return 0;
}
 
// Driver code
int main()
{
    int mat[4][4] = { { 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 } };
 
    // Function call
    search(mat, 4, 29);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C




// C program to search an element in row-wise
// and column-wise sorted matrix
#include <stdio.h>
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
    if (n == 0)
        return -1;
 
    // traverse through the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            // if the element is found
            if (mat[i][j] == x) {
                printf("Element found at (%d, %d)\n", i, j);
                return 1;
            }
    }
 
    printf("Element not found");
    return 0;
}
 
// Driver code
int main()
{
    int mat[4][4] = { { 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 } };
 
    // Function call
    search(mat, 4, 29);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java




// Java program to search an element in row-wise
// and column-wise sorted matrix
 
class GFG {
    static int search(int[][] mat, int n, int x)
    {
        if (n == 0)
            return -1;
 
        // traverse through the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                // if the element is found
                if (mat[i][j] == x) {
                    System.out.print("Element found at ("
                                     + i + ", " + j
                                     + ")\n");
                    return 1;
                }
        }
 
        System.out.print(" Element not found");
        return 0;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int mat[][] = { { 10, 20, 30, 40 },
                        { 15, 25, 35, 45 },
                        { 27, 29, 37, 48 },
                        { 32, 33, 39, 50 } };
 
        // Function call
        search(mat, 4, 29);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Python3




# Python program to search an element in row-wise
# and column-wise sorted matrix
 
# Searches the element x in mat[][]. If the
# element is found, then prints its position
# and returns true, otherwise prints "not found"
# and returns false
 
 
def search(mat, n, x):
    if(n == 0):
        return -1
 
    # Traverse through the matrix
    for i in range(n):
        for j in range(n):
 
            # If the element is found
            if(mat[i][j] == x):
                print("Element found at (", i, ",", j, ")")
                return 1
 
    print(" Element not found")
    return 0
 
 
# Driver code
if __name__ == "__main__":
    mat = [[10, 20, 30, 40], [15, 25, 35, 45],
           [27, 29, 37, 48], [32, 33, 39, 50]]
 
    # Function call
    search(mat, 4, 29)
 
# This code is contributed by rag2127

C#




// C# program to search an element in row-wise
// and column-wise sorted matrix
using System;
 
class GFG {
 
    /* Searches the element x in mat[][]. If the
    element is found, then prints its position
    and returns true, otherwise prints "not found"
    and returns false */
    static int search(int[, ] mat, int n, int x)
    {
        if (n == 0)
            return -1;
 
        // Traverse through the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
 
                // If the element is found
                if (mat[i, j] == x) {
                    Console.Write("Element found at (" + i
                                  + ", " + j + ")\n");
                    return 1;
                }
        }
        Console.Write(" Element not found");
        return 0;
    }
 
    // Driver code
    static public void Main()
    {
        int[, ] mat = { { 10, 20, 30, 40 },
                        { 15, 25, 35, 45 },
                        { 27, 29, 37, 48 },
                        { 32, 33, 39, 50 } };
 
        // Function call
        search(mat, 4, 29);
    }
}
 
// This code is contributed by avanitrachhadiya2155

Javascript




<script>
     
// Java Script program to search an element in row-wise
// and column-wise sorted matrix
 
function search(mat,n,x) {
    if (n == 0)
        return -1;
 
    // traverse through the matrix
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++)
            // if the element is found
            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);
   
//contributed by 171fa07058
</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:-

  1. 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.
  2. 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.
  3. 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++




// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <bits/stdc++.h>
using namespace std;
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
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;
 
    // set indexes for top right element
    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--;
 
        // Check if mat[i][j] < x
        else
            i++;
    }
 
    cout << "n Element not found";
    return 0;
}
 
// Driver code
int main()
{
    int mat[4][4] = { { 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 } };
 
    // Function call
    search(mat, 4, 29);
 
    return 0;
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

C




// C program to search an element in row-wise
// and column-wise sorted matrix
#include <stdio.h>
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
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;
 
    // set indexes for top right element
    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 // if mat[i][j] < x
            i++;
    }
 
    printf("n Element not found");
    return 0; // if ( i==n || j== -1 )
}
 
// Driver code
int main()
{
    int mat[4][4] = {
        { 10, 20, 30, 40 },
        { 15, 25, 35, 45 },
        { 27, 29, 37, 48 },
        { 32, 33, 39, 50 },
    };
 
    // Function call
    search(mat, 4, 29);
    return 0;
}

Java




// JAVA Code for Search in a row wise and
// column wise sorted matrix
 
class GFG {
 
    /* Searches the element x in mat[][]. If the
    element is found, then prints its position
    and returns true, otherwise prints "not found"
    and returns false */
    private static void search(int[][] mat, int n, int x)
    {
 
        // set indexes for top right
        int i = 0, j = n - 1;
        // element
 
        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 // if mat[i][j] < x
                i++;
        }
 
        System.out.print("n Element not found");
        return; // if ( i==n || j== -1 )
    }
    // Driver code
    public static void main(String[] args)
    {
        int mat[][] = { { 10, 20, 30, 40 },
                        { 15, 25, 35, 45 },
                        { 27, 29, 37, 48 },
                        { 32, 33, 39, 50 } };
 
        // Function call
        search(mat, 4, 29);
    }
}
// This code is contributed by Arnav Kr. Mandal.

Python3




# Python3 program to search an element
# in row-wise and column-wise sorted matrix
 
# Searches the element x in mat[][]. If the
# element is found, then prints its position
# and returns true, otherwise prints "not found"
# and returns false
 
 
def search(mat, n, x):
 
    i = 0
 
    # set indexes for top right element
    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
 
        # if mat[i][j] < x
        else:
            i += 1
 
    print("Element not found")
    return 0  # if (i == n || j == -1 )
 
 
# Driver Code
if __name__ == "__main__":
    mat = [[10, 20, 30, 40],
           [15, 25, 35, 45],
           [27, 29, 37, 48],
           [32, 33, 39, 50]]
 
    # Function call
    search(mat, 4, 29)
 
# This code is contributed by Anant Agarwal.

C#




// C# Code for Search in a row wise and
// column wise sorted matrix
using System;
 
class GFG {
    /* Searches the element x in mat[][]. If the
    element is found, then prints its position
    and returns true, otherwise prints "not found"
    and returns false */
    private static void search(int[, ] mat, int n, int x)
    {
        // set indexes for top right
        // element
        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 // if mat[i][j] < x
                i++;
        }
 
        Console.Write("n Element not found");
        return; // if ( i==n || j== -1 )
    }
    // Driver code
    public static void Main()
    {
 
        int[, ] mat = { { 10, 20, 30, 40 },
                        { 15, 25, 35, 45 },
                        { 27, 29, 37, 48 },
                        { 32, 33, 39, 50 } };
 
        // Function call
        search(mat, 4, 29);
    }
}
 
// This code is contributed by Sam007

PHP




<?php
// PHP program to search an
// element in row-wise and
// column-wise sorted matrix
 
/* Searches the element $x
in mat[][]. If the element is
found, then prints its position
and returns true, otherwise prints
"not found" and returns false */
function search(&$mat, $n, $x)
{
    $i = 0;
    $j = $n - 1; // set indexes for
                // top right element
    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 // if $mat[$i][$j] < $x
            $i++;
    }
     
    echo "n Element not found";
    return 0; // if ( $i==$n || $j== -1 )
}
 
// Driver Code
$mat = array(array(10, 20, 30, 40),
            array(15, 25, 35, 45),
            array(27, 29, 37, 48),
            array(32, 33, 39, 50));
 
// Function call
search($mat, 4, 29);
 
// This code is contributed
// by ChitraNayal
?>

Javascript




<script>
// JAVA SCRIPT  Code for Search in a row wise and
// column wise sorted matrix
 
 
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
function search(mat,n,x){
         
    // set indexes for top right
    let i = 0, j = n - 1;
    // element
 
    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 // if mat[i][j] < x
            i++;
    }
 
    document.write("n Element not found");
    return; // if ( i==n || j== -1 )
}
// driver program to test above function
     
    let mat =     [[10, 20, 30, 40 ],
                [ 15, 25, 35, 45 ],
                [ 27, 29, 37, 48 ],
                [ 32, 33, 39, 50 ]];
 
    search(mat, 4, 29);
     
// This code is contributed by bobby
</script>

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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!