Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array | Java program to implement the above approach ; Function to check if it is possible to merge the two given arrays with given conditions ; Stores index of the array A [ ] ; Stores index of the array B [ ] ; Check if the previous element are from the array A [ ] or from the array B [ ] ; Check if it is possible to merge the two given sorted arrays with given conditions ; Traverse both the arrays ; If A [ i ] is less than B [ j ] and previous element are not from A [ ] ; Update prev ; Update i ; If B [ j ] is less than A [ i ] and previous element are not from B [ ] ; Update prev ; Update j ; If A [ i ] equal to B [ j ] ; If previous element are not from B [ ] ; Update prev ; Update j ; If previous element is not from A [ ] ; Update prev ; Update i ; If it is not possible to merge two sorted arrays with given conditions ; Update flag ; Driver Code
import java . io . * ; class GFG { static boolean checkIfPossibleMerge ( int [ ] A , int [ ] B , int N ) { int i = 0 ; int j = 0 ; int prev = - 1 ; boolean flag = true ; while ( i < N && j < N ) { if ( A [ i ] < B [ j ] && prev != 0 ) { prev = 0 ; i ++ ; } else if ( B [ j ] < A [ i ] && prev != 1 ) { prev = 1 ; j ++ ; } else if ( A [ i ] == B [ j ] ) { if ( prev != 1 ) { prev = 1 ; j ++ ; } else { prev = 0 ; i ++ ; } } else { flag = false ; break ; } } return flag ; } public static void main ( String [ ] args ) { int [ ] A = { 3 , 5 , 8 } ; int [ ] B = { 2 , 4 , 6 } ; int N = A . length ; if ( checkIfPossibleMerge ( A , B , N ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }