Check if concatenation of any permutation of given list of arrays generates the given array | 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 ; Given target list ; Given array of list ; Function call
function check ( arr , pieces ) { var m = new Map ( ) ; for ( var i = 0 ; i < arr . length ; i ++ ) m . set ( arr [ i ] , i + 1 ) for ( var i = 0 ; i < pieces . length ; i ++ ) { if ( pieces [ i ] . length == 1 && m . get ( pieces [ i ] [ 0 ] ) != 0 ) { continue ; } else if ( pieces [ i ] . length > 1 && m . get ( pieces [ i ] [ 0 ] ) != 0 ) { var idx = m . get ( pieces [ i ] [ 0 ] ) - 1 ; idx ++ ; if ( idx >= arr . length ) return false ; for ( var j = 1 ; j < pieces [ i ] . length ; j ++ ) { if ( arr [ idx ] == pieces [ i ] [ j ] ) { idx ++ ; if ( idx >= arr . length && j < pieces [ i ] . length - 1 ) return false ; } else { return false ; } } } else { return false ; } } return true ; } var arr = [ 1 , 2 , 4 , 3 ] ; var pieces = [ [ 1 ] , [ 4 , 3 ] , [ 2 ] ] ; if ( check ( arr , pieces ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }