Rearrange array to make product of prefix sum array non zero

Given an array, arr[ ] of size N, the task is to rearrange the given array such that the product of all the elements of its prefix sum array is not equal to 0. If it is not possible to rearrange the array that satisfies the given condition, then print -1.

Examples:

Input: arr[] = {1, -1, -2, 3 }
Output: 3 1 -1 -2
Explanation:
Prefix sum after rearranging the given array to {3, 1, -1, -2} are {3, 4, 3, 1} and product all the elements of its prefix sum array = (3 * 4 * 3 * 1) = 36 .
Therefore, the required array is {3, 1, -1, -2}

Input: arr = {1, 1, -1, -1}
Output: -1

Approach: The idea is to sort the given array either in ascending order or descending order so that any element of its prefix sum not equal to 0. Follow the steps below to solve the problem:



  • Calculate the sum of elements of the given array, say totalSum.
  • If totalSum = 0 then print -1.
  • If totalSum > 0 then print the given array in decreasing order so that any elements of its prefix sum not equal to 0.
  • If totalSum < 0 then print the given array in ascending order so that any elements of its prefix sum not equal to 0.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print array elements
void printArr(int arr[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Function to rearrange array
// that satisfies the given condition
void rearrangeArr(int arr[], int N)
{
    // Stores sum of elements
    // of the given array
    int totalSum = 0;
 
    // Calculate totalSum
    for (int i = 0; i < N; i++) {
        totalSum += arr[i];
    }
 
    // If the totalSum is equal to 0
    if (totalSum == 0) {
 
        // No possible way to
        // rearrange array
        cout << "-1" << endl;
    }
 
    // If totalSum exceeds 0
    else if (totalSum > 0) {
 
        // Rearrange the array
        // in descending order
        sort(arr, arr + N,
             greater<int>());
        printArr(arr, N);
    }
 
    // Otherwise
    else {
 
        // Rearrange the array
        // in ascending order
        sort(arr, arr + N);
        printArr(arr, N);
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, -1, -2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    rearrangeArr(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to print array elements
static void printArr(int arr[], int N)
{
    for(int i = 0; i < N; i++)
    {
        System.out.print(arr[i] + " ");
    }
}
 
// Function to rearrange array
// that satisfies the given condition
static void rearrangeArr(int arr[], int N)
{
     
    // Stores sum of elements
    // of the given array
    int totalSum = 0;
 
    // Calculate totalSum
    for(int i = 0; i < N; i++)
    {
        totalSum += arr[i];
    }
 
    // If the totalSum is equal to 0
    if (totalSum == 0)
    {
         
        // No possible way to
        // rearrange array
        System.out.print("-1" + "\n");
    }
 
    // If totalSum exceeds 0
    else if (totalSum > 0)
    {
         
        // Rearrange the array
        // in descending order
        Arrays.sort(arr);
        arr = reverse(arr);
        printArr(arr, N);
    }
     
    // Otherwise
    else
    {
         
        // Rearrange the array
        // in ascending order
        Arrays.sort(arr);
        printArr(arr, N);
    }
}
 
static int[] reverse(int a[])
{
    int i, n = a.length, t;
    for(i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
    return a;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, -1, -2, 3 };
    int N = arr.length;
     
    rearrangeArr(arr, N);
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to rearrange array
# that satisfies the given condition
def rearrangeArr(arr, N):
     
    # Stores sum of elements
    # of the given array
    totalSum = 0
     
    # Calculate totalSum
    for i in range(N):
        totalSum += arr[i]
 
    # If the totalSum is equal to 0
    if (totalSum == 0):
         
        # No possible way to
        # rearrange array
        print(-1)
 
    # If totalSum exceeds 0
    elif (totalSum > 0):
         
        # Rearrange the array
        # in descending order
        arr.sort(reverse = True)
        print(*arr, sep = ' ')
         
    # Otherwise
    else:
 
        # Rearrange the array
        # in ascending order
        arr.sort()
        print(*arr, sep = ' ')
 
# Driver Code
arr = [ 1, -1, -2, 3 ]
N = len(arr)
 
rearrangeArr(arr, N);
 
# This code is contributed by avanitrachhadiya2155

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to print array elements
static void printArr(int []arr, int N)
{
    for(int i = 0; i < N; i++)
    {
        Console.Write(arr[i] + " ");
    }
}
 
// Function to rearrange array
// that satisfies the given condition
static void rearrangeArr(int []arr, int N)
{
     
    // Stores sum of elements
    // of the given array
    int totalSum = 0;
 
    // Calculate totalSum
    for(int i = 0; i < N; i++)
    {
        totalSum += arr[i];
    }
 
    // If the totalSum is equal to 0
    if (totalSum == 0)
    {
         
        // No possible way to
        // rearrange array
        Console.Write("-1" + "\n");
    }
 
    // If totalSum exceeds 0
    else if (totalSum > 0)
    {
         
        // Rearrange the array
        // in descending order
        Array.Sort(arr);
        arr = reverse(arr);
        printArr(arr, N);
    }
     
    // Otherwise
    else
    {
         
        // Rearrange the array
        // in ascending order
        Array.Sort(arr);
        printArr(arr, N);
    }
}
 
static int[] reverse(int []a)
{
    int i, n = a.Length, t;
    for(i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
    return a;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, -1, -2, 3 };
    int N = arr.Length;
     
    rearrangeArr(arr, N);
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output: 

3 1 -1 -2










 

Time Complexity: O(N logN)
Space Complexity: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.