Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Rearrange Array to maximize sum of MEX of all Subarrays starting from first index
Next article icon

Rearrange array to make sum of all subarrays starting from first index non-zero

Last Updated : 30 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. 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.
  2. 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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to rearrange the array such
// that sum of all elements of subarrays
// from the 1st index is non-zero
void rearrangeArray(int a[], int N)
{
    // Initialize sum of subarrays
    int sum = 0;
 
    // Sum of all elements of array
    for (int i = 0; i < N; i++) {
 
        sum += a[i];
    }
 
    // If sum is 0, the required
    // array could never be formed
    if (sum == 0) {
        cout << "-1";
        return;
    }
 
    // If sum is non zero, array
    // might be formed
    sum = 0;
 
    int b = 0;
 
    // Sort array in ascending order
    sort(a, a + N);
 
    for (int i = 0; i < N; i++) {
        sum += a[i];
 
        // When current subarray sum
        // becomes 0 replace it with
        // the largest element
        if (sum == 0) {
 
            if (a[i] != a[N - 1]) {
 
                sum -= a[i];
 
                // Swap Operation
                swap(a[i], a[N - 1]);
                sum += a[i];
            }
 
            // If largest element is same
            // as element to be replaced,
            // then rearrangement impossible
            else {
                b = 1;
                break;
            }
        }
    }
 
    // If b = 1, then rearrangement
    // is not possible. Hence check
    // with reverse configuration
    if (b == 1) {
 
        b = 0;
        sum = 0;
 
        // Sort array in descending order
        sort(a, a + N, greater<int>());
 
        // When current subarray sum
        // becomes 0 replace it with
        // the smallest element
        for (int i = N - 1; i >= 0; i--) {
 
            sum += a[i];
            if (sum == 0) {
                if (a[i] != a[0]) {
                    sum -= a[i];
 
                    // Swap Operation
                    swap(a[i], a[0]);
                    sum += a[i];
                }
 
                // If smallest element is same
                // as element to be replaced,
                // then rearrangement impossible
                else {
                    b = 1;
                    break;
                }
            }
        }
    }
 
    // If neither of the configurations
    // worked then print "-1"
    if (b == 1) {
        cout << "-1";
        return;
    }
 
    // Otherwise, print the formed
    // rearrangement
    for (int i = 0; i < N; i++) {
        cout << a[i] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, -1, 2, 4, 0 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    rearrangeArray(arr, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
 
class GFG{
 
// Function to rearrange the array such
// that sum of all elements of subarrays
// from the 1st index is non-zero
static void rearrangeArray(int a[], int N)
{
     
    // Initialize sum of subarrays
    int sum = 0;
 
    // Sum of all elements of array
    for(int i = 0; i < N; i++)
    {
        sum += a[i];
    }
 
    // If sum is 0, the required
    // array could never be formed
    if (sum == 0)
    {
        System.out.print("-1");
        return;
    }
 
    // If sum is non zero, array
    // might be formed
    sum = 0;
 
    int b = 0;
 
    // Sort array in ascending order
    Arrays.sort(a);
     
    for(int i = 0; i < N; i++)
    {
        sum += a[i];
 
        // When current subarray sum
        // becomes 0 replace it with
        // the largest element
        if (sum == 0)
        {
            if (a[i] != a[N - 1])
            {
                sum -= a[i];
                 
                // Swap Operation
                int temp = a[i];
                a[i] = a[N - 1];
                a[N - 1] = temp;
                sum += a[i];
            }
 
            // If largest element is same
            // as element to be replaced,
            // then rearrangement impossible
            else
            {
                b = 1;
                break;
            }
        }
    }
 
    // If b = 1, then rearrangement
    // is not possible. Hence check
    // with reverse configuration
    if (b == 1)
    {
        b = 0;
        sum = 0;
 
        // Sort array in descending order
        Arrays.sort(a);
 
        // When current subarray sum
        // becomes 0 replace it with
        // the smallest element
        for(int i = N - 1; i >= 0; i--)
        {
            sum += a[i];
            if (sum == 0)
            {
                if (a[i] != a[0])
                {
                    sum -= a[i];
                     
                    // Swap Operation
                    int temp = a[i];
                    a[i] = a[0];
                    a[0] = temp;
                    sum += a[i];
                }
 
                // If smallest element is same
                // as element to be replaced,
                // then rearrangement impossible
                else
                {
                    b = 1;
                    break;
                }
            }
        }
    }
 
    // If neither of the configurations
    // worked then print "-1"
    if (b == 1)
    {
        System.out.print("-1" + " ");
        return;
    }
 
    // Otherwise, print the formed
    // rearrangement
    for(int i = 0; i < N; i++)
    {
        System.out.print(a[i] + " ");
    }
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given array
    int arr[] = { 1, -1, 2, 4, 0 };
 
    // Size of array
    int N = arr.length;
 
    // Function Call
    rearrangeArray(arr, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR
 
 

Python3




# Python3 program for the above approach
 
# Function to rearrange the array such
# that sum of all elements of subarrays
# from the 1st index is non-zero
def rearrangeArray(a, N):
     
    # Initialize sum of subarrays
    sum = 0
 
    # Sum of all elements of array
    for i in range(N):
        sum += a[i]
 
    # If sum is 0, the required
    # array could never be formed
    if (sum == 0):
        print("-1")
        return
 
    # If sum is non zero, array
    # might be formed
    sum = 0
 
    b = 0
     
    # Sort array in ascending order
    a = sorted(a)
 
    for i in range(N):
        sum += a[i]
 
        # When current subarray sum
        # becomes 0 replace it with
        # the largest element
        if (sum == 0):
            if (a[i] != a[N - 1]):
                sum -= a[i]
 
                # Swap Operation
                a[i], a[N - 1] = a[N - 1], a[i]
                sum += a[i]
 
            # If largest element is same
            # as element to be replaced,
            # then rearrangement impossible
            else:
                b = 1
                break
 
    # If b = 1, then rearrangement
    # is not possible. Hence check
    # with reverse configuration
    if (b == 1):
        b = 0
        sum = 0
 
        # Sort array in descending order
        a = sorted(a)
        a = a[::-1]
 
        # When current subarray sum
        # becomes 0 replace it with
        # the smallest element
        for i in range(N - 1, -1, -1):
            sum += a[i]
             
            if (sum == 0):
                if (a[i] != a[0]):
                    sum -= a[i]
 
                    # Swap Operation
                    a[i], a[0] = a[0], a[i]
                    sum += a[i]
 
                # If smallest element is same
                # as element to be replaced,
                # then rearrangement impossible
                else:
                    b = 1
                    break
 
    # If neither of the configurations
    # worked then print"-1"
    if (b == 1):
        print("-1")
        return
 
    # Otherwise, print the formed
    # rearrangement
    for i in range(N):
        print(a[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [ 1, -1, 2, 4, 0 ]
 
    # Size of array
    N = len(arr)
 
    # Function Call
    rearrangeArray(arr, N)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to rearrange the array such
// that sum of all elements of subarrays
// from the 1st index is non-zero
static void rearrangeArray(int [] a, int N)
{
     
    // Initialize sum of subarrays
    int sum = 0;
 
    // Sum of all elements of array
    for(int i = 0; i < N; i++)
    {
        sum += a[i];
    }
 
    // If sum is 0, the required
    // array could never be formed
    if (sum == 0)
    {
        Console.Write("-1");
        return;
    }
 
    // If sum is non zero, array
    // might be formed
    sum = 0;
 
    int b = 0;
 
    // Sort array in ascending order
    Array.Sort(a);
     
    for(int i = 0; i < N; i++)
    {
        sum += a[i];
         
        // When current subarray sum
        // becomes 0 replace it with
        // the largest element
        if (sum == 0)
        {
            if (a[i] != a[N - 1])
            {
                sum -= a[i];
                 
                // Swap Operation
                int temp = a[i];
                a[i] = a[N - 1];
                a[N - 1] = temp;
                sum += a[i];
            }
             
            // If largest element is same
            // as element to be replaced,
            // then rearrangement impossible
            else
            {
                b = 1;
                break;
            }
        }
    }
     
    // If b = 1, then rearrangement
    // is not possible. Hence check
    // with reverse configuration
    if (b == 1)
    {
        b = 0;
        sum = 0;
         
        // Sort array in descending order
        Array.Sort(a);
 
        // When current subarray sum
        // becomes 0 replace it with
        // the smallest element
        for(int i = N - 1; i >= 0; i--)
        {
            sum += a[i];
            if (sum == 0)
            {
                if (a[i] != a[0])
                {
                    sum -= a[i];
                     
                    // Swap Operation
                    int temp = a[i];
                    a[i] = a[0];
                    a[0] = temp;
                    sum += a[i];
                }
                 
                // If smallest element is same
                // as element to be replaced,
                // then rearrangement impossible
                else
                {
                    b = 1;
                    break;
                }
            }
        }
    }
     
    // If neither of the configurations
    // worked then print "-1"
    if (b == 1)
    {
        Console.Write("-1" + " ");
        return;
    }
     
    // Otherwise, print the formed
    // rearrangement
    for(int i = 0; i < N; i++)
    {
        Console.Write(a[i] + " ");
    }
}
 
// Driver Code
public static void Main()
{
     
    // Given array
    int[] arr = { 1, -1, 2, 4, 0 };
 
    // Size of array
    int N = arr.Length;
 
    // Function Call
    rearrangeArray(arr, N);
}
}
 
// This code is contributed by chitranayal
 
 

Javascript




<script>
// javascript program for the
// above approach
 
// Function to rearrange the array such
// that sum of all elements of subarrays
// from the 1st index is non-zero
function rearrangeArray(a, N)
{
      
    // Initialize sum of subarrays
    let sum = 0;
  
    // Sum of all elements of array
    for(let i = 0; i < N; i++)
    {
        sum += a[i];
    }
  
    // If sum is 0, the required
    // array could never be formed
    if (sum == 0)
    {
        document.write("-1");
        return;
    }
  
    // If sum is non zero, array
    // might be formed
    sum = 0;
  
    let b = 0;
  
    // Sort array in ascending order
    a.sort();
      
    for(let i = 0; i < N; i++)
    {
        sum += a[i];
  
        // When current subarray sum
        // becomes 0 replace it with
        // the largest element
        if (sum == 0)
        {
            if (a[i] != a[N - 1])
            {
                sum -= a[i];
                  
                // Swap Operation
                let temp = a[i];
                a[i] = a[N - 1];
                a[N - 1] = temp;
                sum += a[i];
            }
  
            // If largest element is same
            // as element to be replaced,
            // then rearrangement impossible
            else
            {
                b = 1;
                break;
            }
        }
    }
  
    // If b = 1, then rearrangement
    // is not possible. Hence check
    // with reverse configuration
    if (b == 1)
    {
        b = 0;
        sum = 0;
  
        // Sort array in descending order
        a.sort();
  
        // When current subarray sum
        // becomes 0 replace it with
        // the smallest element
        for(let i = N - 1; i >= 0; i--)
        {
            sum += a[i];
            if (sum == 0)
            {
                if (a[i] != a[0])
                {
                    sum -= a[i];
                      
                    // Swap Operation
                    let temp = a[i];
                    a[i] = a[0];
                    a[0] = temp;
                    sum += a[i];
                }
  
                // If smallest element is same
                // as element to be replaced,
                // then rearrangement impossible
                else
                {
                    b = 1;
                    break;
                }
            }
        }
    }
  
    // If neither of the configurations
    // worked then print "-1"
    if (b == 1)
    {
        document.write("-1" + " ");
        return;
    }
  
    // Otherwise, print the formed
    // rearrangement
    for(let i = 0; i < N; i++)
    {
        document.write(a[i] + " ");
    }
}
  
// Driver Code
 
    // Given array
    let arr = [ 1, -1, 2, 4, 0 ];
  
    // Size of array
    let N = arr.length;
  
    // Function Call
    rearrangeArray(arr, N);
           
</script>
 
 
Output: 
-1 0 4 2 1

 

Time Complexity: O(N*log N)
Auxiliary Space: O(1)



Next Article
Rearrange Array to maximize sum of MEX of all Subarrays starting from first index
author
costheta_z
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Searching
  • Sorting
  • array-rearrange
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Searching
  • Sorting

Similar Reads

  • Rearrange Array to maximize sum of MEX of all Subarrays starting from first index
    Given an array arr[] of N elements ranging from 0 to N-1(both included), the task is to rearrange the array such that the sum of all the MEX from every subarray starting from index 0 is maximum. Duplicates can be present in the array. MEX of an array is the first non-negative element that is missing
    8 min read
  • First subarray with negative sum from the given Array
    Given an array arr[] consisting of N integers, the task is to find the start and end indices of the first subarray with a Negative Sum. Print "-1" if no such subarray exists. Note: In the case of multiple negative-sum subarrays in the given array, the first subarray refers to the subarray with the l
    15+ min read
  • Find all subarray index ranges in given Array with set bit sum equal to X
    Given an array arr (1-based indexing) of length N and an integer X, the task is to find and print all index ranges having a set bit sum equal to X in the array. Examples: Input: A[] = {1 4 3 5 7}, X = 4Output: (1, 3), (3, 4)Explanation: In the above array subarray having set bit sum equal to X (= 4)
    15 min read
  • 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}Outpu
    7 min read
  • Minimum Decrements on Subarrays required to reduce all Array elements to zero
    Given an array arr[] consisting of N non-negative integers, the task is to find the minimum number of subarrays that needs to be reduced by 1 such that all the array elements are equal to 0. Example: Input: arr[] = {1, 2, 3, 2, 1}Output: 3Explanation: Operation 1: {1, 2, 3, 2, 1} -> {0, 1, 2, 1,
    5 min read
  • Rearrange an Array such that Sum of same-indexed subsets differ from their Sum in the original Array
    Given an array A[] consisting of N distinct integers, the task is to rearrange the given array such that the sum of every same-indexed non-empty subsets of size less than N, is not equal to their sum in the original array.Examples: Input: A[] = {1000, 100, 10, 1} Output: 100 10 1 1000 Explanation: O
    6 min read
  • Minimum operations to make Array sum at most S from given Array
    Given an array arr[], of size N and an integer S, the task is to find the minimum operations to make the sum of the array less than or equal to S. In each operation: Any element can be chosen and can be decremented by 1, orCan be replaced by any other element in the array. Examples: Input: arr[]= {1
    10 min read
  • Sum of minimum element of all subarrays of a sorted array
    Given a sorted array A of n integers. The task is to find the sum of the minimum of all possible subarrays of A. Examples: Input: A = [ 1, 2, 4, 5] Output: 23 Subsequences are [1], [2], [4], [5], [1, 2], [2, 4], [4, 5] [1, 2, 4], [2, 4, 5], [1, 2, 4, 5] Minimums are 1, 2, 4, 5, 1, 2, 4, 1, 2, 1. Sum
    4 min read
  • Maximize non decreasing Array size by replacing Subarray with sum
    Given an array arr[] of size N. In one operation only one subarray can be selected and replaced with the sum of the subarray. The task is to find the maximum size of the array after making it non-decreasing. Examples: Input: N = 5, arr[] = {5, 1, 6, 6, 6}Output: 4Explanation: maximum size non-decrea
    15+ min read
  • Maximize point to reduce Array by replacing Subarray with its sum
    Given an array arr[] of size, N, the task is to maximize the score to reduce the array to a single element by replacing any subarray with its sum where the score of one such operation is the product of subarray length and the minimum value of that subarray. Examples:Input: N = 2, arr[] = {1, 5}Outpu
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences