Check if concatenation of any permutation of given list of arrays generates the given array | Java 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
import java . util . * ; class GFG { static boolean check ( List < Integer > arr , ArrayList < List < Integer > > pieces ) { Map < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) m . put ( arr . get ( i ) , i ) ; for ( int i = 0 ; i < pieces . size ( ) ; i ++ ) { if ( pieces . get ( i ) . size ( ) == 1 && m . containsKey ( pieces . get ( i ) . get ( 0 ) ) ) { continue ; } else if ( pieces . get ( i ) . size ( ) > 1 && m . containsKey ( pieces . get ( i ) . get ( 0 ) ) ) { int idx = m . get ( pieces . get ( i ) . get ( 0 ) ) ; idx ++ ; if ( idx >= arr . size ( ) ) return false ; for ( int j = 1 ; j < pieces . get ( i ) . size ( ) ; j ++ ) { if ( arr . get ( idx ) . equals ( pieces . get ( i ) . get ( j ) ) ) { idx ++ ; if ( idx >= arr . size ( ) && j < pieces . get ( i ) . size ( ) - 1 ) return false ; } else { return false ; } } } else { return false ; } } return true ; } public static void main ( String [ ] args ) { List < Integer > arr = Arrays . asList ( 1 , 2 , 4 , 3 ) ; ArrayList < List < Integer > > pieces = new ArrayList < > ( ) ; pieces . add ( Arrays . asList ( 1 ) ) ; pieces . add ( Arrays . asList ( 4 , 3 ) ) ; pieces . add ( Arrays . asList ( 2 ) ) ; if ( check ( arr , pieces ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }