Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Search in a 2D matrix

Easy
0/40
profile
Contributed by
16 upvotes
Asked in companies
Phone PeSamsungWipro

Problem statement

You are given a 2-D matrix with 'N' rows and 'M' columns, each row of the matrix is sorted in non-decreasing order and the first element of each row is greater than or equal to the last element of the previous row. You are also given an integer ‘X’, you are supposed to find whether 'X' is present in the given matrix or not.

Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains a single integer ‘T’ denoting the number of test cases. The test cases are as follows.

The first line of each test case contains three integers ‘X’, ‘N’ and ‘M’ separated by a single space denoting the element to be searched, the number of rows in the matrix, and the number of columns in the matrix respectively.

The next ‘N’ lines contain ‘M’ integers each denoting the elements of the matrix.
Output Format :
For each test case, print “Yes”(without quotes) if ‘X’ is present in the matrix otherwise print “No”.

Print the output of each test case on a new line. 
Note :
You don’t need to print anything; It has already been taken care of.
Constraints :
1 <= T <= 50
1 <= X <= 10 ^ 6
1 <= N, M <= 100
-10 ^ 6 <= ARR[i][j] <= 10 ^ 6

Where ‘T’ denotes the number of test cases, ‘N’ denotes the number of rows in a matrix, ‘M’ denotes the number of columns in the matrix and ARR[i][j] denotes the j-th element of the i’th row of the given matrix.

Time Limit: 1 sec
Sample Input 1 :
2
4 2 2
2 4
8 12
7 3 4
1 2 4 5
8 12 14 16
23 25 26 29
Sample Output 1 :
Yes
No
Explanation of Sample Input 1 :
In the first test case, the 2nd element of the first row is equal to 4, hence the output is “Yes”.

In the second test case, 7 is not present in the matrix hence the output is “No”.
Sample Input 2 :
2
2 1 1
2
22 3 2
3 4
11 17
23 27
Sample Output 2 :
Yes
No
Explanation of Sample Input 2 :
In the first test case, the only element is equal to 2, hence the output is “Yes”.

In the second test case, 22 is not present in the matrix hence the output is “No”.
Hint

Can you try to iterate through the matrix?

Approaches (3)
Brute force Approach

The idea is to iterate through the matrix and check if any element is equal to ‘X’.

 

The steps are as follows :

  1. Iterate from 0 to ‘N’, let’s say the current index is ‘i’, this will represent our current row.
    1. Iterate from 0 to ‘M’, let’s say the current index is ‘j’, this will represent the current column of the matrix.
      1. If arr[i][j] is equal to ‘X’ return true as we have found an element equal to ‘X’.
  2. If there is no element equal to ‘X’ return false.
Time Complexity

O(N*M), where ‘N’ is the number of rows and ‘M’ is the number of columns in the matrix.

 

We are iterating through the matrix which has ‘N’ rows and each row has ‘M’ elements, thus the total elements are N*M. Thus, the overall time complexity is O(N*M).

Space Complexity

O(1).

 

We are using constant space. Thus, the overall space complexity is O(1).

Code Solution
(100% EXP penalty)
Search in a 2D matrix
All tags
Sort by
Search icon

Interview problems

C++ || beat 100% || Easy code

#include <bits/stdc++.h> 

bool findInMatrix(int x, vector<vector<int>> &arr)

{

    int row = arr.size();

    int col = arr[0].size();

    

    int start = 0;

    int end = row*col-1;

 

    int mid = start + (end - start)/2;

    

    while(start <= end ){

        int element = arr[mid/col][mid%col];

        if(element == x){

            return 1;

        }

        if(element < x){

            start = mid +1;

        }

        else {

            end = mid-1;

        }

        mid = start + (end - start)/2;

    }

    return 0;

}

24 views
0 replies
0 upvotes

Interview problems

Binary search Method

#include <bits/stdc++.h>

bool findInMatrix(int target, std::vector<std::vector<int>> &matrix) {  
    int numRows = matrix.size();
    int numCols = matrix[0].size();
    int left = 0, right = numRows * numCols - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        int midCol = mid % numCols;
        int midRow = mid / numCols;
        int midVal = matrix[midRow][midCol];

        if (midVal == target) {
            return true;
        }
        if (midVal < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
}
63 views
0 replies
0 upvotes

Interview problems

C++ Search in a 2D matrix - 3 approachs

#include <bits/stdc++.h>

bool findInMatrix(int x, vector<vector<int>> &arr)

{

//Write your code here

 

// 1st approach - Binary search

int row=0;

int col= arr[row].size() -1;

while(row < arr.size() && col >= 0){

if(arr[row][col]== x){

return true;

}

if(arr[row][col]< x){

row++;

}

else{

col--;

}

}

return false;

 

// 2nd approach - Improved Binary search  

int row = arr.size();

int col= arr[0].size();

int l=0,h=row*col -1;

 

while(l<=h){

int mid = l+(h-l)/2;

int tC= mid % col;

int tR= mid/col;

int val = arr[tR][tC];

 

if(val==x){

return true;

}

if(val<x){

l=mid+1;

}

else{

h=mid-1;

}

}

 

return false;

 

// 3rd approach - Linear Search

 

for(int i=0;i<arr.size();i++){

for(int j=0;j<arr[i].size();j++){

if(arr[i][j]==x){

return true;

}

}

}

return false;  

}

 

datastructures

Binary Search

Linear Search

40 views
0 replies
0 upvotes

Interview problems

C++ simple iterative

#include <bits/stdc++.h> 

bool findInMatrix(int x, vector<vector<int>> &arr)

{

    int n=arr.size(),m=arr[0].size();

    for(int i=0;i<n;i++)

    {

        for(int j=0;j<m;j++)

        {

           if(arr[i][j]==x)

            return true;

        }

    }

    return false;

}

67 views
0 replies
0 upvotes

Interview problems

C++ Solution

#include <bits/stdc++.h> 

bool findInMatrix(int x, vector<vector<int>> &arr)

{

    

    int i = arr.size()-1;

    int j = 0;

    while(i>=0 && j<arr[0].size()){

        if(arr[i][j] == x){

            return true;

        }

        else if(arr[i][j] < x){

            j++;

        }

        else{

            i--;

        }

    }

    return false;

}

48 views
0 replies
0 upvotes

Interview problems

Binary Search Solution to apply in each row!!

#include <bits/stdc++.h>
bool findInMatrix(int x, vector<vector<int>> &arr) {
  for (int i = 0; i < arr.size(); i++) {
    int low = 0, high = arr[0].size() - 1;
    while (low <= high) {
      int mid = low + (high - low) / 2;
      if (arr[i][mid] == x)
        return true;
      else if (arr[i][mid] < x)
        low = mid + 1;
      else
        high = mid - 1;
    }
  }

  return false;
}
62 views
0 replies
0 upvotes

Interview problems

Beats 91% using Binary Search

#include <bits/stdc++.h> 

bool findInMatrix(int x, vector<vector<int>> &arr)

{

    int res;

    for(vector<int>temp  : arr){

        int low = 0 , high=temp.size()-1;

        if(temp[high] <x || temp[low] > x){

            continue;

        }

        else{

            while(low<=high){

                int mid = low+(high-low)/2;

                if(temp[mid] == x){

                    return true;

                }

                else if(temp[mid] < x){

                    low= mid+1;

                }

                else{

                    high=mid-1;

                }

            }

        }

    }

    return false;

}

81 views
0 replies
0 upvotes

Interview problems

Intuition Explained ✅ | Beginner Friendly | Approaches Explained 👌 | Beats 94%

Intuition : We can solve the question in 1 of 3 ways :

  1.  Using Linear Search (Average approach)
  2. Using Binary Search to find row to iterate, and then use binary search again to search for element in found row (Better Approach)
  3. Using Binary Search on whole Array (Best Approach)

 

 

Approach 1 of using linear Search is pretty much obvious for anyone to solve on their own.

 

Approach 2: 

  1. Find rowSize, and colSize.
  2. To find the row in which our element might lie, just Initialize Start = 0, and end = rowSize-1.
  3. Calculate mid and compare it with 1 of 3 conditions:
    1. If x is greater than last element of curRow ( x > arr[mid][colSize-1] ), then update start = mid + 1.
    2. If x is less than first element of curRow ( x < arr[mid][0] ), then update end = mid - 1;
    3. otherwise, the x lies in curRow, so break the loop.
  4. If our loop is broken by our break condition, then our start and end variables satisfies (start ≤ end) condition, if it doesn't, it simply means, that no row exist that contains our targetElement. So return false immediately.
  5. Now we have row, we can find the targetElement in specific row, using binarySearch.

 

 

 

Approach 3:  On carefully analyzing, we can observe that, the whole matrix is sorted, so if we convert the whole matrix into 1D array, giving each element the index from 0 to (n*m) - 1. We will be having the sorted 1D array.

But we won't convert it actually, we will simply assume that each element has index from 0 to (n*m) - 1.

Now if we want to calculate the rowIndex and colIndex for 6th element or index = 5, we just need to reduce the matrix problem into 1D array by asking two questions:

 

To calculate rowIndex, colIndex of index = 5 or element no. 6th in 1D Array):

 

  1. How many full rows will be consumed, if we want to place 5 in our matrix having colSize of 4. We can find it using => index / colSize = 5 / 4 => 1. Meaning the 1 full row will be consumed. So our curIndex would lie in row 2. But, since we follow 0 based indexing, row 2 will be considered as 1. So, we can directly use the 5/4 => 1, as our rowNum.
  2. What will be my column number, if we want to reduce our curNum in a range from 0 to colSize - 1. We can find it using => index % colSize = 5 % 4 => 1.

 

So our index 5 or element no. 6th in 1D Array will be on [1][1] index in matrix.

Now we have the way to get rowIndex and colIndex of any element present in our imaginary 1D array. So, we all are smart enought to put binary search to use, to get the search done for target Element.

 

 

92 views
0 replies
1 upvote

Interview problems

Binary search for 2D ARRAY Java

import java.util.ArrayList;

 

public class Solution {

    public static boolean findInMatrix(int x, ArrayList<ArrayList<Integer>> arr) {

        int totalRows = arr.size();

        int totalColumns = arr.get(0).size();

        int low = 0;

        int high = totalRows * totalColumns - 1;

 

        while (low <= high) {

            int mid = low + (high - low) / 2;

            int midRow = mid / totalColumns;

            int midCol = mid % totalColumns;

            int midValue = arr.get(midRow).get(midCol);

 

            if (midValue == x) {

                return true;

            } else if (midValue < x) {

                low = mid + 1;

            } else {

                high = mid - 1;

            }

        }

 

        return false;

    }

}

 

163 views
0 replies
0 upvotes

Interview problems

Optimized Solution : Apporach : Binary search

bool findInMatrix(int x, vector<vector<int>> &arr)

{

    int row=arr.size();

        int col=arr[0].size();

      int start=0;

      int end=(row*col)-1;

      

      while(start<=end){

          int mid=start+(end-start)/2;

          int element=arr[mid/col][mid%col];

          if(element==x){

              return 1;

          }

          if(element<x){

              start=mid+1;

          }

          else{

              end=mid-1;

          }

      }

     return 0; 

}

beginners

programming

datastructures

algorithms

95 views
0 replies
1 upvote
Full screen
Console