Please check it. It is not passing the last case

hello @atreyyash

  for(int h=0;h<n;h++)
    {
        for(int i=0;i<m;i++)
        {
            if(a[h][end_col]<key)
            {
                break;
            }
            else if(a[i][end_col]>key)
            {
                end_col--;
            }
            else if(a[i][end_col]==key)
            {
				cnt++;
                // cout<<"Key found at "<<h<<", "<<end_col<<"index";
                return 1;
            }
        }
    }

this code is wrong. u r mixing brute force and divide and conquer in the same solution.

also ur inner loop is to iterate columnwise but u r accessing row (see a[i][end_col] )

refer this->

  for(int row = 0;row < n;) {
        for(int col=m-1;col>=0 and row < n;) {
            if(arr[row][col] == key) {
               
                return 1;
            } else if(arr[row][col] > key) {
                col--;
            } else {
                row++;
            }
        }
    }

return 0;

or refer this->

// set indexes for top right element
    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--;
       
        // Check if mat[i][j] < x
        else
            i++;
    }
 
    cout << "n Element not found";
    return 0;

but i have implemented staircase method, done from video.

i checked the video, in that video bhaiya only explained the technique and the implementation is similar to above code.

check this in case algorithm is not clear->

  1. Let the given element be x, create two variable i = 0, j = n-1 as index of row and column
  2. Run a loop until i = 0
  3. Check if the current element is greater than x then decrease the count of j. Exclude the current column.
  4. Check if the current element is less than x then increase the count of i. Exclude the current row.
  5. If the element is equal then print the position and end.

can binary search be implemented

on 2d matrix? no . . . . . . .

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.