Test case 1 fails

import java.util.;
import java.io.
;

public class Main {

public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

        int[][] matrix = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }


        int target = sc.nextInt();

        System.out.println(search2dBinary(matrix, target));
}

static int search2dBinary(int[][] matrix, int target) {
if(matrix.length==0)
return 0;

    int r = matrix.length;
    if (r == 0) return 0;
    int c = matrix[0].length;

    int lo = 0;
    int high = (r * c) - 1;

    while (lo <= high) {
        int mid = (lo + (high - lo) / 2);
        int midEle = matrix[mid / c][mid % c];
        if (midEle == target) {
            return 1;
        } else if (midEle < target) {
            lo = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return 0;
}

}

Hey @vivek4988_7c34775e05f479ae It is good practice to give some specific problem you are facing it will be beneficial for me to give solution on time. So please tell me the problem you’re
facing specifically.

Hello @pssharma1410 , well this whole code is working in leetcode but not working in cb editor.
There are three testcases , 1st and 3rd shows success and 2nd one showing failure and I don’t know what that testcase which is failing . so help me with the correcting the code , if I’m doing anything wrong , I used binary search

Hey @vivek4988_7c34775e05f479ae. You cannot apply binary search in coding blocks question bcoz in coding blocks question you are not given that the array is sorted.The array given is unsorted.So do this question by linear search.

Yeah get it but it is mentioned here that Given an n x m matrix, where every row and column is sorted in increasing order. can you please help me what I’m doing wrong ? its working just one case not working.

Sorry if I hurt you in some case , you looks offensive today :blush:

Hey @vivek4988_7c34775e05f479ae No I am totally fine Really sorry if you feel like I was offensive. This code might help you.

public static int searchMatrix(int[][] matrix, int item) {
        int row = 0;
        int col = matrix[0].length - 1;
        while (row < matrix.length && col >= 0) {

            if (matrix[row][col] == item) {
                return 1;
            } else if (matrix[row][col] > item) {
                col--;
            } else {
                row++;
            }
        }

        return 0;
    }

Thanks , this is working

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.