Check if concatenation of any permutation of given list of arrays generates the given array | Python3 program for the above approach ; Function to check if it is possible to obtain array by concatenating the arrays in list pieces [ ] ; Stores the index of element in the given array arr [ ] ; Traverse over the list pieces ; If item size is 1 and exists in map ; If item contains > 1 element then check order of element ; If end of the array ; Check the order of elements ; If order is same as the array elements ; Increment idx ; If order breaks ; Otherwise ; Return false if the first element doesn 't exist in m ; Return true ; Driver Code ; Given target list ; Given array of list ; Function call
from array import * NEW_LINE def check ( arr , pieces ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT m [ arr [ i ] ] = i + 1 NEW_LINE DEDENT for i in range ( 0 , len ( pieces ) ) : NEW_LINE INDENT if ( len ( pieces [ i ] ) == 1 and m [ pieces [ i ] [ 0 ] ] != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( len ( pieces [ i ] ) > 1 and m [ pieces [ i ] [ 0 ] ] != 0 ) : NEW_LINE INDENT idx = m [ pieces [ i ] [ 0 ] ] - 1 NEW_LINE idx = idx + 1 NEW_LINE if idx >= len ( arr ) : NEW_LINE INDENT return False NEW_LINE DEDENT for j in range ( 1 , len ( pieces [ i ] ) ) : NEW_LINE INDENT if arr [ idx ] == pieces [ i ] [ j ] : NEW_LINE INDENT idx = idx + 1 NEW_LINE if ( idx >= len ( arr ) and j < len ( pieces [ i ] ) - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 3 ] NEW_LINE pieces = [ [ 1 ] , [ 4 , 3 ] , [ 2 ] ] NEW_LINE if check ( arr , pieces ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT