Restore a permutation from the given helper array | Function to find the required permutation ; Each element in P ' is like a  cumulative sum in Q ; minval is the minimum value in P ' ; To check if each entry in P is from the range [ 1 , n ] ; Invalid permutation ; If a valid permutation exists ; Print the permutation ; No valid permutation ; Driver code
function findPerm ( Q , n ) { var minval = 0 , qsum = 0 ; for ( var i = 0 ; i < n - 1 ; i ++ ) { qsum += Q [ i ] ; if ( qsum < minval ) minval = qsum ; } var P = Array ( n ) ; P [ 0 ] = 1 - minval ; var permFound = true ; for ( var i = 0 ; i < n - 1 ; i ++ ) { P [ i + 1 ] = P [ i ] + Q [ i ] ; if ( P [ i + 1 ] > n P [ i + 1 ] < 1 ) { permFound = false ; break ; } } if ( permFound ) { for ( var i = 0 ; i < n ; i ++ ) { document . write ( P [ i ] + " " ) ; } } else { document . write ( - 1 ) ; } } var Q = [ - 2 , 1 ] ; var n = 1 + Q . length ; findPerm ( Q , n ) ;