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:
Number of subarrays for which product and sum are equal
Next article icon

Number of times an array can be partitioned repetitively into two subarrays with equal sum

Last Updated : 04 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N, the task is to find the number of times the array can be partitioned repetitively into two subarrays such that the sum of the elements of both the subarrays is the same.

Examples: 

Input: arr[] = { 2, 2, 2, 2 } 
Output: 3 
Explanation: 
1. Make the first partition after index 1. Remaining arrays are {2, 2} on the right side and left side both. 
2. Consider the left subarray {2, 2}. Make a partition after index 0 of this left subarray. 
Now two similar subarrays with one element each i.e. {2} are formed which cannot be sub-divided. 
3. Consider the right subarray {2, 2}. Make a partition after index 0 of this left subarray. 
Now two similar subarrays with one element each i.e. {2} are formed which cannot be sub-divided. 
Hence the output is 3 as the array was partitioned 3 times.

Input: arr[] = {12, 3, 3, 0, 3, 3} 
Output: 4 
Explanation: 
1. The first partition is after index 0. Remaining array is arr[] = {3, 3, 0, 3, 3}. 
2. The second partition is after index 1. The remaining array is {3, 3}, and {0, 3, 3}. 
3. The third partition is after index 0 in array {3, 3}. 
4. The fourth partition is after 1 in the array {0, 3, 3} 
The remaining array is {0, 3}, and {3} which cannot be sub-divided. 
Hence the output is 4. 

Approach: The idea is to use Recursion. Below are the steps:  

  1. Find the prefix-sum of the given array arr[] and store it in an array pref[].
  2. Iterate from the start position to the end position.
  3. For each possible partition index(say K), if prefix_sum[K] – prefix_sum[start-1] = prefix_sum[end] – prefix_sum[k] then the partition is valid.
  4. If a partition is valid in the above step then proceed with the left and right sub-arrays separately and determine whether these two subarrays form a valid partition or not.
  5. Repeat the step 3 and 4 for both the left and right partition until any further partition isn’t possible.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Recursion Function to calculate the
// possible splitting
int splitArray(int start, int end,
               int* arr,
               int* prefix_sum)
{
    // If there are less than
    // two elements, we cannot
    // partition the sub-array.
    if (start >= end)
        return 0;
 
    // Iterate from the start
    // to end-1.
    for (int k = start; k < end; ++k) {
 
        if ((prefix_sum[k] - prefix_sum[start - 1])
            == (prefix_sum[end] - prefix_sum[k])) {
 
            // Recursive call to the left
            // and the right sub-array.
            return 1 + splitArray(start,
                                  k,
                                  arr,
                                  prefix_sum)
                   + splitArray(k + 1,
                                end,
                                arr,
                                prefix_sum);
        }
    }
 
    // If there is no such partition,
    // then return 0
    return 0;
}
 
// Function to find the total splitting
void solve(int arr[], int n)
{
 
    // Prefix array to store
    // the prefix-sum using
    // 1 based indexing
    int prefix_sum[n + 1];
 
    prefix_sum[0] = 0;
 
    // Store the prefix-sum
    for (int i = 1; i <= n; ++i) {
        prefix_sum[i] = prefix_sum[i - 1]
                        + arr[i - 1];
    }
 
    // Function Call to count the
    // number of splitting
    cout << splitArray(1, n,
                       arr,
                       prefix_sum);
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 12, 3, 3, 0, 3, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    solve(arr, N);
    return 0;
}
 
 

Java




// Java program for the above approach
class GFG{
 
// Recursion Function to calculate the
// possible splitting
static int splitArray(int start, int end,
                      int[] arr,
                      int[] prefix_sum)
{
    // If there are less than
    // two elements, we cannot
    // partition the sub-array.
    if (start >= end)
        return 0;
 
    // Iterate from the start
    // to end-1.
    for (int k = start; k < end; ++k)
    {
        if ((prefix_sum[k] - prefix_sum[start - 1]) ==
            (prefix_sum[end] - prefix_sum[k]))
        {
 
            // Recursive call to the left
            // and the right sub-array.
            return 1 + splitArray(start, k, arr, prefix_sum) +
                       splitArray(k + 1, end, arr, prefix_sum);
        }
    }
 
    // If there is no such partition,
    // then return 0
    return 0;
}
 
// Function to find the total splitting
static void solve(int arr[], int n)
{
 
    // Prefix array to store
    // the prefix-sum using
    // 1 based indexing
    int []prefix_sum = new int[n + 1];
 
    prefix_sum[0] = 0;
 
    // Store the prefix-sum
    for (int i = 1; i <= n; ++i)
    {
        prefix_sum[i] = prefix_sum[i - 1] +
                               arr[i - 1];
    }
 
    // Function Call to count the
    // number of splitting
    System.out.print(splitArray(1, n, arr,
                                prefix_sum));
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array
    int arr[] = { 12, 3, 3, 0, 3, 3 };
    int N = arr.length;
 
    // Function call
    solve(arr, N);
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python3 program for the above approach
 
# Recursion Function to calculate the
# possible splitting
def splitArray(start, end, arr, prefix_sum):
     
    # If there are less than
    # two elements, we cannot
    # partition the sub-array.
    if (start >= end):
        return 0
 
    # Iterate from the start
    # to end-1.
    for k in range(start, end):
        if ((prefix_sum[k] - prefix_sum[start - 1]) ==
            (prefix_sum[end] - prefix_sum[k])) :
 
            # Recursive call to the left
            # and the right sub-array.
            return (1 + splitArray(start, k, arr,
                                   prefix_sum) +
                        splitArray(k + 1, end, arr,
                                   prefix_sum))
         
    # If there is no such partition,
    # then return 0
    return 0
 
# Function to find the total splitting
def solve(arr, n):
 
    # Prefix array to store
    # the prefix-sum using
    # 1 based indexing
    prefix_sum = [0] * (n + 1)
 
    prefix_sum[0] = 0
 
    # Store the prefix-sum
    for i in range(1, n + 1):
        prefix_sum[i] = (prefix_sum[i - 1] +
                                arr[i - 1])
     
    # Function Call to count the
    # number of splitting
    print(splitArray(1, n, arr, prefix_sum))
 
# Driver Code
 
# Given array
arr = [ 12, 3, 3, 0, 3, 3 ]
N = len(arr)
 
# Function call
solve(arr, N)
 
# This code is contributed by sanjoy_62
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Recursion Function to calculate the
// possible splitting
static int splitArray(int start, int end,
                      int[] arr,
                      int[] prefix_sum)
{
     
    // If there are less than
    // two elements, we cannot
    // partition the sub-array.
    if (start >= end)
        return 0;
 
    // Iterate from the start
    // to end-1.
    for(int k = start; k < end; ++k)
    {
       if ((prefix_sum[k] -
            prefix_sum[start - 1]) ==
           (prefix_sum[end] -
            prefix_sum[k]))
       {
            
           // Recursive call to the left
           // and the right sub-array.
           return 1 + splitArray(start, k, arr,
                                 prefix_sum) +
                      splitArray(k + 1, end, arr,
                                 prefix_sum);
       }
    }
     
    // If there is no such partition,
    // then return 0
    return 0;
}
 
// Function to find the total splitting
static void solve(int []arr, int n)
{
     
    // Prefix array to store
    // the prefix-sum using
    // 1 based indexing
    int []prefix_sum = new int[n + 1];
 
    prefix_sum[0] = 0;
 
    // Store the prefix-sum
    for(int i = 1; i <= n; ++i)
    {
       prefix_sum[i] = prefix_sum[i - 1] +
                              arr[i - 1];
    }
 
    // Function Call to count the
    // number of splitting
    Console.Write(splitArray(1, n, arr,
                             prefix_sum));
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []arr = { 12, 3, 3, 0, 3, 3 };
    int N = arr.Length;
 
    // Function call
    solve(arr, N);
}
}
 
// This code is contributed by Amit Katiyar
 
 

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Recursion Function to calculate the
// possible splitting
function splitArray(start, end, arr, prefix_sum)
{
    // If there are less than
    // two elements, we cannot
    // partition the sub-array.
    if (start >= end)
        return 0;
   
    // Iterate from the start
    // to end-1.
    for (let k = start; k < end; ++k)
    {
        if ((prefix_sum[k] - prefix_sum[start - 1]) ==
            (prefix_sum[end] - prefix_sum[k]))
        {
   
            // Recursive call to the left
            // and the right sub-array.
            return 1 + splitArray(start, k, arr, prefix_sum) +
                       splitArray(k + 1, end, arr, prefix_sum);
        }
    }
   
    // If there is no such partition,
    // then return 0
    return 0;
}
   
// Function to find the total splitting
function solve(arr, n)
{
   
    // Prefix array to store
    // the prefix-sum using
    // 1 based indexing
    let prefix_sum = Array.from({length: n+1}, (_, i) => 0);
   
    prefix_sum[0] = 0;
   
    // Store the prefix-sum
    for (let i = 1; i <= n; ++i)
    {
        prefix_sum[i] = prefix_sum[i - 1] +
                               arr[i - 1];
    }
   
    // Function Call to count the
    // number of splitting
   document.write(splitArray(1, n, arr,
                                prefix_sum));
}
 
// Driver code
 
    // Given array
    let arr = [ 12, 3, 3, 0, 3, 3 ];
    let N = arr.length;
   
    // Function call
    solve(arr, N);
 
// This code is contributed by code_hunt.
</script>
 
 
Output: 
4

 

Time Complexity: O(N2) 
Auxiliary Space: O(N)
 



Next Article
Number of subarrays for which product and sum are equal

S

shreyasshetty788
Improve
Article Tags :
  • Advanced Data Structure
  • Arrays
  • Backtracking
  • Competitive Programming
  • DSA
  • Greedy
  • Recursion
  • Searching
  • Arrays
  • prefix-sum
  • subarray
Practice Tags :
  • Advanced Data Structure
  • Arrays
  • Arrays
  • Backtracking
  • Greedy
  • prefix-sum
  • Recursion
  • Searching

Similar Reads

  • Count number of ways array can be partitioned such that same numbers are present in same subarray
    Given an array A[] of size N. The Task for this problem is to count several ways to partition the given array A[] into continuous subarrays such that the same integers are not present in different subarrays. Print the answer modulo 109 + 7. Examples: Input: A[] = {1, 2, 1, 3} Output: 2Explanation: T
    11 min read
  • Count of Subsets that can be partitioned into two non empty sets with equal Sum
    Given an array Arr[] of size N, the task is to find the count of subsets of Arr[] that can be partitioned into two non-empty groups having equal sum. Examples: Input: Arr[] = {2, 3, 4, 5}Output: 2Explanation: The subsets are: {2, 3, 5} which can be split into {2, 3} and {5}{2, 3, 4, 5} which can be
    15+ min read
  • Number of subarrays for which product and sum are equal
    Given a array of n numbers. We need to count the number of subarrays having the product and sum of elements are equal Examples: Input : arr[] = {1, 3, 2} Output : 4 The subarrays are : [0, 0] sum = 1, product = 1, [1, 1] sum = 3, product = 3, [2, 2] sum = 2, product = 2 and [0, 2] sum = 1+3+2=6, pro
    5 min read
  • Check if it possible to partition in k subarrays with equal sum
    Given an array A of size N, and a number K. Task is to find out if it is possible to partition the array A into K contiguous subarrays such that the sum of elements within each of these subarrays is the same. Prerequisite: Count the number of ways to divide an array into three contiguous parts havin
    15+ min read
  • Partition an array into two subsets with equal count of unique elements
    Given an array arr[] consisting of N integers, the task is to partition the array into two subsets such that the count of unique elements in both the subsets is the same and for each element, print 1 if that element belongs to the first subset. Otherwise, print 2. If it is not possible to do such a
    13 min read
  • Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
    Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might no
    15+ min read
  • Partition of a set into k subsets with equal sum using BitMask and DP
    Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset. Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
    9 min read
  • Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
    Given an array arr[] consisting of N integers, the task is to count the number of ways to split the array into two subarrays of equal sum after changing a single array element to 0. Examples: Input: arr[] = {1, 2, -1, 3}Output: 4Explanation: Replacing arr[0] by 0, arr[] is modified to {0, 2, -1, 3}.
    11 min read
  • Partition of a set into K subsets with equal sum
    Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset. Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
    9 min read
  • Find an element which divides the array in two subarrays with equal product
    Given, an array of size N. Find an element which divides the array into two sub-arrays with equal product. Print -1 if no such partition is not possible. Examples : Input : 1 4 2 1 4 Output : 2 If 2 is the partition, subarrays are : {1, 4} and {1, 4} Input : 2, 3, 4, 1, 4, 6 Output : 1 If 1 is the p
    12 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