check if first array is sorted and if there are consecutive duplicate elements check second array at the index of duplicate elements

In your case (4) it return true, because in your code you have if (a [i] < a[i+1]) return true inside the loop that check the duplicated values. So in array1 (1 < 2) is true, hence it return true. How to solve this issue, you have to divide your code in two parts.

    1. check if the first array is sorted a good explanation is in stackoverflow.com/a/19458302/3429103,
    1. your code to complete the verification of same value successive and check in the second array.

something like

public class Main
{
    public static boolean isSorted(int[] a) 
    {
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i] > a[i + 1]) 
            {
                return false;
            }
        }

        return true;
    }
    
    public static boolean checkDuplicate(int[] a, int b[]) 
    {
        for (int i = 0; i < a.length - 1; i++) 
        {
            if (a[i] == a[i + 1] && b[i] > b[i + 1]) 
            {
                return false;
            }
        }

        return true;
    }
    
    public static void main(String[] args) 
    { 
        int array1[]={1,2,3,3,4}; 
        int array2[]={5,6,4,3,2};
        
        if(isSorted(array1) && checkDuplicate(array1,array2))
            System.out.println("True");
        else
            System.out.println("False");
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top