Search In A Sorted 2D Matrix

Moderate
0/80
profile
Contributed by
34 upvotes
Asked in companies
CIS - Cyber InfrastructurePhonePeJP Morgan

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.
Detailed explanation ( Input/output format, Notes, Images )
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.
Sample Input 1:
3 3
1 3 7
10 12 15
19 20 21
12
Sample Output 1:
1
Explanation Of Sample Input 1:
Input:
'MATRIX' = [ [1, 3, 7], [10, 12, 15], [19, 20, 21] ], 'TARGET' = 12 
Output: 1

Explanation: Since the given number ‘TARGET’ is present in the matrix, we return true.
Sample Input 2:
4 4
1 5 9 13
14 15 16 17
19 20 21 50
59 60 71 80
80
Sample Output 2:
1
Constraints:
1 <= 'N', 'M' <=10^5
1 <= 'MATRIX [ i ] [ j ]', 'TARGET' <= 10^9
The sum of N*M over all test cases is less than 2*10^5.
Time Limit: 1 sec
Hint

Linearly traverse the complete matrix.

Approaches (2)
Naive 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.
Time Complexity

O( N*M ), Where ‘N’ and ‘M’ are the given matrix ‘MATRIX’ dimensions. 

 

We use two nested loops of O(N) and O(M), respectively. Hence, the overall complexity will be O( N*M ).

Space Complexity

O( 1 ). 

 

We are taking O( 1 ) extra space for elements. Hence, the overall complexity will be O( 1 ).

Code Solution
(100% EXP penalty)
Search In A Sorted 2D Matrix
Full screen
Console