Check if a Sequence is a concatenation of two permutations | Function to Check if a given sequence is a concatenation of two permutations or not ; Computing the sum of all the elements in the array ; Computing the prefix sum for all the elements in the array ; Iterating through the i from lengths 1 to n - 1 ; Sum of first i + 1 elements ; Sum of remaining n - i - 1 elements ; Lengths of the 2 permutations ; Checking if the sums satisfy the formula or not ; Driver Code
function checkPermutation ( arr , n ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; let prefix = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; prefix [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) prefix [ i ] = prefix [ i - 1 ] + arr [ i ] ; for ( let i = 0 ; i < n - 1 ; i ++ ) { let lsum = prefix [ i ] ; let rsum = sum - prefix [ i ] ; let l_len = i + 1 , r_len = n - i - 1 ; if ( ( ( 2 * lsum ) == ( l_len * ( l_len + 1 ) ) ) && ( ( 2 * rsum ) == ( r_len * ( r_len + 1 ) ) ) ) return true ; } return false ; } let arr = [ 1 , 2 , 5 , 3 , 4 , 1 , 2 ] ; let n = arr . length ; if ( checkPermutation ( arr , n ) ) document . write ( " " ) ; else document . write ( " " ) ;