Restore a permutation from the given helper array | Java implementation of the approach ; 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
class GFG { static void findPerm ( int Q [ ] , int n ) { int minval = 0 , qsum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { qsum += Q [ i ] ; if ( qsum < minval ) minval = qsum ; } int [ ] P = new int [ n ] ; P [ 0 ] = 1 - minval ; boolean permFound = true ; for ( int 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 ( int i = 0 ; i < n ; i ++ ) { System . out . print ( P [ i ] + " ▁ " ) ; } } else { System . out . print ( - 1 ) ; } } public static void main ( String [ ] args ) { int Q [ ] = { - 2 , 1 } ; int n = 1 + Q . length ; findPerm ( Q , n ) ; } }