Last Updated: 23 Nov, 2022

Search In A Sorted 2D Matrix

Moderate
Asked in companies
CIS - Cyber InfrastructurePhonePe

Problem statement

You are given a 2D matrix ‘MATRIX’ of ‘N’*’M’ dimension. You must check whether a given number ‘target’ is present in the matrix.


The following properties apply to the given matrix:

1. In each row, integers are sorted from left to right.
2. Each row's first integer is greater than the previous row's last integer.

Example:

Input:
'MATRIX' = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60] ], 'TARGET' = 3 
Output:1
Explanation: Since the given number ‘TARGET’ is present in the matrix, we return true.
Input Format:
The first line of the input will contain two integers denoting the dimensions of the matrix ‘N’ and ‘M’. 
The following 'N' lines contain ‘M’ integers.
The next line contains an integer ‘TARGET’.
Output Format:-
The only line contains 1 if 'TARGET' is present otherwise, 0.
Note:-
You don’t need to print anything. Just implement the given function.

Approaches

01 Approach

Approach:

  • We can iterate through every element in the matrix and return true if any element in the matrix is equal to the ‘TARGET’ integer.
  • If the traversal is complete, we can return false because no element in the matrix equals the ‘TARGET’ integer.

 

Algorithm:

Function bool searchElement([int][int] MATRIX, int TARGET):

  1. For ‘i’ from 0 to ‘N’-1:
    • For ‘j’ from 0 to ‘M’-1:
      • If ‘MATRIX[ i ][ j ]’ == ‘TARGET’:
        • Return true.
  2. Return false.

02 Approach

Approach:

  • Given that the given matrix will be sorted row-wise and column-wise, we can see that the elements in the matrix will be in a monotonically increasing order.
  • Consider the 2D matrix as a 1D matrix with indices ranging from 0 to ( N*M )-1 and use binary search on it.

 

Algorithm:

Function bool searchElement([int][int] MATRIX, int TARGET):

  1. Initialize two integer variables, ‘low’ and ‘high’, to 0 and (N*M -1), respectively.
  2. While ‘low’ <= ‘high’:
    • Int ‘mid’ = ‘low’ + ( ‘high’ - ‘low’ ) / 2.
    • Int ‘i’ = ‘mid’ / M and ‘j’ = ‘mid’ % ‘M’.
    • If ‘MATRIX[i][j]’ == ‘TARGET’:
      • Return true.
    • If ‘MATRIX[i][j]’ < ‘TARGET’:
      • ‘low’ = ‘mid’ + 1.
    • Else:
      • ‘high’ = ‘mid’ - 1.
  3. Return false.