Rearrange array to make sum of all subarrays starting from first index non-zero
Last Updated :
30 Jun, 2022
Given an array arr[] consisting of N integers, the task is to rearrange the array such that sum of all subarrays starting from the first index of the array is non-zero. If it is not possible to generate such arrangement, then print “-1”.
Examples:
Input: arr[] = {-1, 1, -2, 3}
Output: {-1, -2, 1, 3}
Explanation: One of the possible rearrangement is {-1, -2, 1, 3}.
Subarrays starting from index 0 are {-1}, {-1, -2}, {-1, -2, 1} and {-1, -2, 1, 3}. None of the above subarrays have sum 0.
Input: arr[] = {0, 0, 0, 0}
Output: -1
Approach: Desired array can be obtained from the given array if it is in any of the following two configurations:
- If the given array is sorted in ascending order, the first subarray with sum zero can be handled by replacing the last element of the subarray with an element greater than it.
- Similarly, in arrays sorted in descending order, by replacing the first element of the subarray with sum zero with an element smaller than it to ensure that the sum thereafter is negative.
Follow the steps below to solve the problem:
- When array is sorted in ascending order:
- Sort the array arr[] in ascending order and find the sum of the first i elements of the array (0 ? i ? N).
- When a zero-sum encountered, replace the element nullifying the prefix sum (i.e., ith element) with the largest element of the array:
- If the largest element of the array is equal to the integer causing nullification, then move to the second configuration.
- If the largest element is greater than the problematic element, this replacement ensures positive-sum instead of zero.
- When array is sorted in descending order:
- Sort the array arr[] in descending order and start finding the sum of the last i elements of the array (0 ? i ? N).
- When zero-sum is encountered, replace the element nullifying the prefix sum (i.e. ith element) with the smallest element of the array:
- If the smallest element of the array is equal to the integer causing nullification, then it’s not possible to rearrange the array arr[].
- If the smallest element is smaller than the problematic element, this replacement ensures a negative-sum instead of zero.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void rearrangeArray( int a[], int N)
{
int sum = 0;
for ( int i = 0; i < N; i++) {
sum += a[i];
}
if (sum == 0) {
cout << "-1" ;
return ;
}
sum = 0;
int b = 0;
sort(a, a + N);
for ( int i = 0; i < N; i++) {
sum += a[i];
if (sum == 0) {
if (a[i] != a[N - 1]) {
sum -= a[i];
swap(a[i], a[N - 1]);
sum += a[i];
}
else {
b = 1;
break ;
}
}
}
if (b == 1) {
b = 0;
sum = 0;
sort(a, a + N, greater< int >());
for ( int i = N - 1; i >= 0; i--) {
sum += a[i];
if (sum == 0) {
if (a[i] != a[0]) {
sum -= a[i];
swap(a[i], a[0]);
sum += a[i];
}
else {
b = 1;
break ;
}
}
}
}
if (b == 1) {
cout << "-1" ;
return ;
}
for ( int i = 0; i < N; i++) {
cout << a[i] << " " ;
}
}
int main()
{
int arr[] = { 1, -1, 2, 4, 0 };
int N = sizeof (arr) / sizeof (arr[0]);
rearrangeArray(arr, N);
return 0;
}
|
Java
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
class GFG{
static void rearrangeArray( int a[], int N)
{
int sum = 0 ;
for ( int i = 0 ; i < N; i++)
{
sum += a[i];
}
if (sum == 0 )
{
System.out.print( "-1" );
return ;
}
sum = 0 ;
int b = 0 ;
Arrays.sort(a);
for ( int i = 0 ; i < N; i++)
{
sum += a[i];
if (sum == 0 )
{
if (a[i] != a[N - 1 ])
{
sum -= a[i];
int temp = a[i];
a[i] = a[N - 1 ];
a[N - 1 ] = temp;
sum += a[i];
}
else
{
b = 1 ;
break ;
}
}
}
if (b == 1 )
{
b = 0 ;
sum = 0 ;
Arrays.sort(a);
for ( int i = N - 1 ; i >= 0 ; i--)
{
sum += a[i];
if (sum == 0 )
{
if (a[i] != a[ 0 ])
{
sum -= a[i];
int temp = a[i];
a[i] = a[ 0 ];
a[ 0 ] = temp;
sum += a[i];
}
else
{
b = 1 ;
break ;
}
}
}
}
if (b == 1 )
{
System.out.print( "-1" + " " );
return ;
}
for ( int i = 0 ; i < N; i++)
{
System.out.print(a[i] + " " );
}
}
public static void main(String args[])
{
int arr[] = { 1 , - 1 , 2 , 4 , 0 };
int N = arr.length;
rearrangeArray(arr, N);
}
}
|
Python3
def rearrangeArray(a, N):
sum = 0
for i in range (N):
sum + = a[i]
if ( sum = = 0 ):
print ( "-1" )
return
sum = 0
b = 0
a = sorted (a)
for i in range (N):
sum + = a[i]
if ( sum = = 0 ):
if (a[i] ! = a[N - 1 ]):
sum - = a[i]
a[i], a[N - 1 ] = a[N - 1 ], a[i]
sum + = a[i]
else :
b = 1
break
if (b = = 1 ):
b = 0
sum = 0
a = sorted (a)
a = a[:: - 1 ]
for i in range (N - 1 , - 1 , - 1 ):
sum + = a[i]
if ( sum = = 0 ):
if (a[i] ! = a[ 0 ]):
sum - = a[i]
a[i], a[ 0 ] = a[ 0 ], a[i]
sum + = a[i]
else :
b = 1
break
if (b = = 1 ):
print ( "-1" )
return
for i in range (N):
print (a[i], end = " " )
if __name__ = = '__main__' :
arr = [ 1 , - 1 , 2 , 4 , 0 ]
N = len (arr)
rearrangeArray(arr, N)
|
C#
using System;
class GFG{
static void rearrangeArray( int [] a, int N)
{
int sum = 0;
for ( int i = 0; i < N; i++)
{
sum += a[i];
}
if (sum == 0)
{
Console.Write( "-1" );
return ;
}
sum = 0;
int b = 0;
Array.Sort(a);
for ( int i = 0; i < N; i++)
{
sum += a[i];
if (sum == 0)
{
if (a[i] != a[N - 1])
{
sum -= a[i];
int temp = a[i];
a[i] = a[N - 1];
a[N - 1] = temp;
sum += a[i];
}
else
{
b = 1;
break ;
}
}
}
if (b == 1)
{
b = 0;
sum = 0;
Array.Sort(a);
for ( int i = N - 1; i >= 0; i--)
{
sum += a[i];
if (sum == 0)
{
if (a[i] != a[0])
{
sum -= a[i];
int temp = a[i];
a[i] = a[0];
a[0] = temp;
sum += a[i];
}
else
{
b = 1;
break ;
}
}
}
}
if (b == 1)
{
Console.Write( "-1" + " " );
return ;
}
for ( int i = 0; i < N; i++)
{
Console.Write(a[i] + " " );
}
}
public static void Main()
{
int [] arr = { 1, -1, 2, 4, 0 };
int N = arr.Length;
rearrangeArray(arr, N);
}
}
|
Javascript
<script>
function rearrangeArray(a, N)
{
let sum = 0;
for (let i = 0; i < N; i++)
{
sum += a[i];
}
if (sum == 0)
{
document.write( "-1" );
return ;
}
sum = 0;
let b = 0;
a.sort();
for (let i = 0; i < N; i++)
{
sum += a[i];
if (sum == 0)
{
if (a[i] != a[N - 1])
{
sum -= a[i];
let temp = a[i];
a[i] = a[N - 1];
a[N - 1] = temp;
sum += a[i];
}
else
{
b = 1;
break ;
}
}
}
if (b == 1)
{
b = 0;
sum = 0;
a.sort();
for (let i = N - 1; i >= 0; i--)
{
sum += a[i];
if (sum == 0)
{
if (a[i] != a[0])
{
sum -= a[i];
let temp = a[i];
a[i] = a[0];
a[0] = temp;
sum += a[i];
}
else
{
b = 1;
break ;
}
}
}
}
if (b == 1)
{
document.write( "-1" + " " );
return ;
}
for (let i = 0; i < N; i++)
{
document.write(a[i] + " " );
}
}
let arr = [ 1, -1, 2, 4, 0 ];
let N = arr.length;
rearrangeArray(arr, N);
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...