RunTime error in one testcase in Kth element of two sorted arrays

28 Views Asked by At

here's the link to the problem in coding ninjas:

https://www.codingninjas.com/studio/problems/1112629?topList=striver-sde-sheet-problems&utm_source=striver&utm_medium=website

here's my code:

public class Solution {
    public static int ninjaAndLadoos(int row1[], int row2[], int m, int n, int k) {
        // Write your code here.

        if(m>n){
            return ninjaAndLadoos(row2, row1, n, m, k);
        }

        int low=Math.max(k-m,0);
        int high=Math.min(k,n);


        while(low<=high){

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

            int cut2=k-cut1;

            int l1 = cut1 == 0 ? Integer.MIN_VALUE : row1[cut1 - 1]; 
            int l2 = cut2 == 0 ? Integer.MIN_VALUE : row2[cut2 - 1];
            int r1 = cut1 == n ? Integer.MAX_VALUE : row1[cut1]; 
            int r2 = cut2 == m ? Integer.MAX_VALUE : row2[cut2];


            if(l1<=r2 && l2<=r1){
                return Math.max(l1,l2);
            }

            else if(l1>r2){
                high=cut1-1;
            }
            
            else{
                low=cut1+1;
            }
        }

        return -1;
       
    }
}

its failing in these test cases(getting as run time error) : 2 6 12 18 2 3 9 9 10 11 1 1 2 4 5 6 7 8 8 9 9 13 10 8 5

please make changes in code such that it should pass these test cases

0

There are 0 best solutions below