Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array | 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
def checkIfPossibleMerge ( A , B , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE prev = - 1 NEW_LINE flag = 1 NEW_LINE while ( i < N and j < N ) : NEW_LINE INDENT if ( A [ i ] < B [ j ] and prev != 0 ) : NEW_LINE INDENT prev = 0 NEW_LINE i += 1 NEW_LINE DEDENT elif ( B [ j ] < A [ i ] and prev != 1 ) : NEW_LINE INDENT prev = 1 NEW_LINE j += 1 NEW_LINE DEDENT elif ( A [ i ] == B [ j ] ) : NEW_LINE INDENT if ( prev != 1 ) : NEW_LINE INDENT prev = 1 NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prev = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT return flag NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 5 , 8 ] NEW_LINE B = [ 2 , 4 , 6 ] NEW_LINE N = len ( A ) NEW_LINE if ( checkIfPossibleMerge ( A , B , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT