Count number of ways to divide an array into two halves with same sum

Given an integer array of N elements. The task is to find the number of ways to split the array into two equal sum sub-arrays of non-zero lengths.
Examples:Â
Input: arr[] = {0, 0, 0, 0}
Output: 3Â
Explanation:
All the possible ways are: { {{0}, {0, 0, 0}}, {{0, 0}, {0, 0}}, {{0, 0, 0}, {0}}Â
Therefore, the required output is 3.Input: {1, -1, 1, -1}
Output: 1
Â
Â
Simple Solution: A simple solution is to generate all the possible contiguous sub-arrays pairs and find there sum. If their sum is the same, we will increase the count by one.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The idea is to take an auxiliary array say, aux[] to calculate the presum of the array such that for an index i aux[i] will store the sum of all elements from index 0 to index i.
By doing this we can calculate the left sum and right sum for every index of the array in constant time.Â
So, the idea is to:Â
Â
- Find the sum of all the numbers of the array and store it in a variable say, S. If the sum is odd, then the answer will be 0.
- Traverse the array and keep calculating the sum of elements. At ith step, we will use the variable S to maintain sum of all the elements from index 0 to i.Â
- Calculate sum upto the ith index.
- If this sum equals S/2, increase the count of the number of ways by 1.
- Do this from i=0 to i=N-2.
Below is the implementation of the above approach:Â
Â
C++
// C++ program to count the number of ways to// divide an array into two halves// with the same sumÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to count the number of ways to// divide an array into two halves// with same sumint cntWays(int arr[], int n){    // if length of array is 1    // answer will be 0 as we have    // to split it into two    // non-empty halves    if (n == 1)        return 0;Â
    // variables to store total sum,    // current sum and count    int tot_sum = 0, sum = 0, ans = 0;Â
    // finding total sum    for (int i = 0; i < n; i++)        tot_sum += arr[i];Â
    // checking if sum equals total_sum/2    for (int i = 0; i < n - 1; i++) {        sum += arr[i];        if (sum == tot_sum / 2)            ans++;    }Â
    return ans;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 1, -1, 1, -1, 1, -1 };Â
    int n = sizeof(arr) / sizeof(int);Â
    cout << cntWays(arr, n);Â
    return 0;} |
Java
// Java program to count the number of ways to// divide an array into two halves// with the same sumimport java.util.*;import java.io.*;class GFG {Â
    // Function to count the number of ways to    // divide an array into two halves    // with same sum    static int cntWays(int arr[], int n)    {        // if length of array is 1        // answer will be 0 as we have        // to split it into two        // non-empty halves        if (n == 1)         {            return 0;        }Â
        // variables to store total sum,        // current sum and count        int tot_sum = 0, sum = 0, ans = 0;Â
        // finding total sum        for (int i = 0; i < n; i++)         {            tot_sum += arr[i];        }Â
        // checking if sum equals total_sum/2        for (int i = 0; i < n - 1; i++)         {            sum += arr[i];            if (sum == tot_sum / 2)            {                ans++;            }        }Â
        return ans;    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[] = {1, -1, 1, -1, 1, -1};Â
        int n = arr.length;Â
        System.out.println(cntWays(arr, n));    }}Â
// This code contributed by Rajput-Ji |
Python3
# Python program to count the number of ways to # divide an array into two halves # with the same sum Â
# Function to count the number of ways to # divide an array into two halves # with same sum def cntWays(arr, n):     # if length of array is 1     # answer will be 0 as we have     # to split it into two     # non-empty halves     if (n == 1):         return 0; Â
    # variables to store total sum,     # current sum and count     tot_sum = 0; sum = 0; ans = 0; Â
    # finding total sum     for i in range(0,n):         tot_sum += arr[i]; Â
    # checking if sum equals total_sum/2     for i in range(0,n-1):        sum += arr[i];         if (sum == tot_sum / 2):            ans+=1;     return ans; Â
# Driver Code arr = [1, -1, 1, -1, 1, -1 ]; Â
n = len(arr); Â
print(cntWays(arr, n)); Â
# This code contributed by PrinciRaj1992 |
C#
// C# program to count the number of ways to// divide an array into two halves with// the same sumusing System; Â
class GFG {Â
    // Function to count the number of ways to    // divide an array into two halves    // with same sum    static int cntWays(int []arr, int n)    {        // if length of array is 1        // answer will be 0 as we have        // to split it into two        // non-empty halves        if (n == 1)         {            return 0;        }Â
        // variables to store total sum,        // current sum and count        int tot_sum = 0, sum = 0, ans = 0;Â
        // finding total sum        for (int i = 0; i < n; i++)         {            tot_sum += arr[i];        }Â
        // checking if sum equals total_sum/2        for (int i = 0; i < n - 1; i++)         {            sum += arr[i];            if (sum == tot_sum / 2)            {                ans++;            }        }Â
        return ans;    }Â
    // Driver Code    public static void Main()    {        int []arr = {1, -1, 1, -1, 1, -1};Â
        int n = arr.Length;Â
        Console.WriteLine(cntWays(arr, n));    }}Â
// This code contributed by anuj_67.. |
Javascript
<script>Â
      // JavaScript program to count the number of ways to      // divide an array into two halves      // with the same sumÂ
      // Function to count the number of ways to      // divide an array into two halves      // with same sum      function cntWays(arr, n)       {        // if length of array is 1        // answer will be 0 as we have        // to split it into two        // non-empty halves        if (n == 1) return 0;Â
        // variables to store total sum,        // current sum and count        var tot_sum = 0,          sum = 0,          ans = 0;Â
        // finding total sum        for (var i = 0; i < n; i++) tot_sum += arr[i];Â
        // checking if sum equals total_sum/2        for (var i = 0; i < n - 1; i++) {          sum += arr[i];          if (sum == tot_sum / 2)           ans++;        }Â
        return ans;      }Â
      // Driver Code      var arr = [1, -1, 1, -1, 1, -1];      var n = arr.length;      document.write(cntWays(arr, n));       </script> |
2
Â
Time Complexity: O(N), since there runs a loop from 0 to (n – 1)
Auxiliary Space: O(1), since no extra space has been taken.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



