Rearrange array to make sum of all subarrays starting from first index non | Function to rearrange the array such that sum of all elements of subarrays from the 1 st index is non - zero ; Initialize sum of subarrays ; Sum of all elements of array ; If sum is 0 , the required array could never be formed ; If sum is non zero , array might be formed ; Sort array in ascending order ; When current subarray sum becomes 0 replace it with the largest element ; Swap Operation ; If largest element is same as element to be replaced , then rearrangement impossible ; If b = 1 , then rearrangement is not possible . Hence check with reverse configuration ; Sort array in descending order ; When current subarray sum becomes 0 replace it with the smallest element ; Swap Operation ; If smallest element is same as element to be replaced , then rearrangement impossible ; If neither of the configurations worked then pr " - 1" ; Otherwise , print the formed rearrangement ; Driver Code ; Given array ; Size of array ; Function Call
def rearrangeArray ( a , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT sum = 0 NEW_LINE b = 0 NEW_LINE a = sorted ( a ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT if ( a [ i ] != a [ N - 1 ] ) : NEW_LINE INDENT sum -= a [ i ] NEW_LINE a [ i ] , a [ N - 1 ] = a [ N - 1 ] , a [ i ] NEW_LINE sum += a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT b = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( b == 1 ) : NEW_LINE INDENT b = 0 NEW_LINE sum = 0 NEW_LINE a = sorted ( a ) NEW_LINE a = a [ : : - 1 ] NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT if ( a [ i ] != a [ 0 ] ) : NEW_LINE INDENT sum -= a [ i ] NEW_LINE a [ i ] , a [ 0 ] = a [ 0 ] , a [ i ] NEW_LINE sum += a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT b = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( b == 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , - 1 , 2 , 4 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE rearrangeArray ( arr , N ) NEW_LINE DEDENT