Skip to content
Related Articles
Check if it possible to partition in k subarrays with equal sum
• Difficulty Level : Medium
• Last Updated : 05 May, 2021

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 having equal sum

Examples :

```Input : arr[] = { 1, 4, 2, 3, 5 } K = 3
Output : Yes
Explanation :
Three possible partitions which have equal sum :
(1 + 4), (2 + 3) and (5)

Input : arr[] = { 1, 1, 2, 2 } K = 2
Output : No```

Approach :
Can be solved by using Prefix Sums. Firstly, note that total sum of all elements in the array should be divisible by K to create K partitions each having equal sum. If it is divisible then, check each partition have an equal sum by doing :
1. For a particular K, each subarray should have a required sum = total_sum / K.
2. Starting from the 0th index, start comparing prefix sum, as soon as
it is equal to the sum, it implies the end of one subarray (let’s say at index j).
3. From (j + 1)th index, find another suitable i whose sum (prefix_sum[i] –
prefix_sum[j]) gets equal to the required sum. And the process goes until
required number of contiguous subarrays i.e. K is found.
4. If at any index, any subarray sum becomes greater than required sum, break out
from loop since each subarray should contain that an equal sum.

Following is the implementation for above Approach

## C++

 `// CPP Program to check if array``// can be split into K contiguous``// subarrays each having equal sum``#include ``using` `namespace` `std;` `// function returns true to it is possible to``// create K contiguous partitions each having``// equal sum, otherwise false``bool` `KpartitionsPossible(``int` `arr[], ``int` `n, ``int` `K)``{``    ``// Creating and filling prefix sum array``    ``int` `prefix_sum[n];``    ``prefix_sum = arr;``    ``for` `(``int` `i = 1; i < n; i++)``        ``prefix_sum[i] =  prefix_sum[i - 1] + arr[i];` `    ``// return false if total_sum is not``    ``// divisible by K  ``    ``int` `total_sum = prefix_sum[n-1];``    ``if` `(total_sum % K != 0)``        ``return` `false``;` `    ``// a temporary variable to check``    ``// there are exactly K partitions``    ``int` `temp = 0;``    ` `    ``int` `pos = -1;``    ``for` `(``int` `i = 0; i < n; i++)``    ``{       ``        ``// find suitable i for which first``        ``// partition have the required sum``        ``// and then find next partition and so on``        ``if` `(prefix_sum[i] - (pos == -1 ? 0 :``            ``prefix_sum[pos]) == total_sum / K)``        ``{``            ``pos = i;``            ``temp++;``        ``}``        ` `        ``// if it becomes greater than``        ``// required sum break out``        ``else` `if` `(prefix_sum[i] - prefix_sum[pos] >``                ``total_sum / K)``            ``break``;``    ``}` `    ``// check if temp has reached to K``    ``return` `(temp == K);``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 4, 4, 3, 5, 6, 2 };   ``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `K = 3;``    ``if` `(KpartitionsPossible(arr, n, K))``        ``cout << ``"Yes"``;``    ``else``        ``cout << ``"No"``;``    ``return` `0;``}`

## Java

 `// Java Program to check if an array``// can be split into K contiguous``// subarrays each having equal sum``public` `class` `GfG{` `    ``// Function returns true to it is possible to``    ``// create K contiguous partitions each having``    ``// equal sum, otherwise false``    ``static` `boolean` `KpartitionsPossible(``int` `arr[], ``int` `n, ``int` `K)``    ``{``        ``// Creating and filling prefix sum array``        ``int` `prefix_sum[] = ``new` `int``[n];``        ``prefix_sum[``0``] = arr[``0``];``        ``for` `(``int` `i = ``1``; i < n; i++)``            ``prefix_sum[i] = prefix_sum[i - ``1``] + arr[i];``    ` `        ``// return false if total_sum is not divisible by K``        ``int` `total_sum = prefix_sum[n-``1``];``        ``if` `(total_sum % K != ``0``)``            ``return` `false``;``    ` `        ``// a temporary variable to check``        ``// there are exactly K partitions``        ``int` `temp = ``0``, pos = -``1``;``        ` `        ``for` `(``int` `i = ``0``; i < n; i++)``        ``{        ``            ``// find suitable i for which first``            ``// partition have the required sum``            ``// and then find next partition and so on``            ``if` `(prefix_sum[i] - (pos == -``1` `? ``0` `:``                ``prefix_sum[pos]) == total_sum / K)``            ``{``                ``pos = i;``                ``temp++;``            ``}``            ` `            ``// if it becomes greater than``            ``// required sum break out``            ``else` `if` `(prefix_sum[i] - (pos == -``1` `? ``0` `:``                ``prefix_sum[pos]) > total_sum / K)``                ``break``;``        ``}``    ` `        ``// check if temp has reached to K``        ``return` `(temp == K);``    ``}` `     ``public` `static` `void` `main(String []args){``        ` `        ``int` `arr[] = { ``4``, ``4``, ``3``, ``5``, ``6``, ``2` `};    ``        ``int` `n = arr.length;``    ` `        ``int` `K = ``3``;``        ``if` `(KpartitionsPossible(arr, n, K))``            ``System.out.println(``"Yes"``);``        ``else``            ``System.out.println(``"No"``);``     ``}``}` `// This code is contributed by Rituraj Jain`

## Python3

 `# Python 3 Program to check if array``# can be split into K contiguous``# subarrays each having equal sum` `# function returns true to it is possible to``# create K contiguous partitions each having``# equal sum, otherwise false``def` `KpartitionsPossible(arr, n, K):``    ` `    ``# Creating and filling prefix sum array``    ``prefix_sum ``=` `[``0` `for` `i ``in` `range``(n)]``    ``prefix_sum[``0``] ``=` `arr[``0``]``    ``for` `i ``in` `range``(``1``, n, ``1``):``        ``prefix_sum[i] ``=` `prefix_sum[i ``-` `1``] ``+` `arr[i]` `    ``# return false if total_sum is not``    ``# divisible by K``    ``total_sum ``=` `prefix_sum[n ``-` `1``]``    ``if` `(total_sum ``%` `K !``=` `0``):``        ``return` `False` `    ``# a temporary variable to check``    ``# there are exactly K partitions``    ``temp ``=` `0``    ` `    ``pos ``=` `-``1``    ``for` `i ``in` `range``(``0``, n, ``1``):``        ` `        ``# find suitable i for which first``        ``# partition have the required sum``        ``# and then find next partition and so on``        ``if` `(pos ``=``=` `-``1``):``            ``sub ``=` `0``        ``else``:``            ``sub ``=` `prefix_sum[pos]``        ``if` `(prefix_sum[i] ``-` `sub ``=``=` `total_sum ``/` `K) :``            ``pos ``=` `i``            ``temp ``+``=` `1``        ` `        ``# if it becomes greater than``        ``# required sum break out``        ``elif` `(prefix_sum[i] ``-``              ``prefix_sum[pos] > total_sum ``/` `K):``            ``break` `    ``# check if temp has reached to K``    ``return` `(temp ``=``=` `K)` `# Driver Code``if` `__name__ ``=``=``'__main__'``:``    ``arr ``=` `[``4``, ``4``, ``3``, ``5``, ``6``, ``2``]``    ``n ``=` `len``(arr)` `    ``K ``=` `3``    ``if` `(KpartitionsPossible(arr, n, K)):``        ``print``(``"Yes"``)``    ``else``:``        ``print``(``"No"``)` `# This code is contributed by``# Shashank_Sharma`

## C#

 `// C# Program to check if an array``// can be split into K contiguous``// subarrays each having equal sum``using` `System;` `class` `GfG``{` `    ``// Function returns true to it is possible to``    ``// create K contiguous partitions each having``    ``// equal sum, otherwise false``    ``static` `bool` `KpartitionsPossible(``int``[] arr, ``int` `n, ``int` `K)``    ``{``        ``// Creating and filling prefix sum array``        ``int``[] prefix_sum = ``new` `int``[n];``        ``prefix_sum = arr;``        ``for` `(``int` `i = 1; i < n; i++)``            ``prefix_sum[i] = prefix_sum[i - 1] + arr[i];``    ` `        ``// return false if total_sum is not divisible by K``        ``int` `total_sum = prefix_sum[n-1];``        ``if` `(total_sum % K != 0)``            ``return` `false``;``    ` `        ``// a temporary variable to check``        ``// there are exactly K partitions``        ``int` `temp = 0, pos = -1;``        ` `        ``for` `(``int` `i = 0; i < n; i++)``        ``{        ``            ``// find suitable i for which first``            ``// partition have the required sum``            ``// and then find next partition and so on``            ``if` `(prefix_sum[i] - (pos == -1 ? 0 :``                ``prefix_sum[pos]) == total_sum / K)``            ``{``                ``pos = i;``                ``temp++;``            ``}``            ` `            ``// if it becomes greater than``            ``// required sum break out``            ``else` `if` `(prefix_sum[i] - (pos == -1 ? 0 :``                ``prefix_sum[pos]) > total_sum / K)``                ``break``;``        ``}``    ` `        ``// check if temp has reached to K``        ``return` `(temp == K);``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ` `        ``int``[] arr = { 4, 4, 3, 5, 6, 2 };    ``        ``int` `n = arr.Length;``    ` `        ``int` `K = 3;``        ``if` `(KpartitionsPossible(arr, n, K))``            ``Console.WriteLine(``"Yes"``);``        ``else``            ``Console.WriteLine(``"No"``);``    ``}``}` `// This code is contributed by ChitraNayal`

## PHP

 ``

## Javascript

 ``
Output:

`Yes`

Time Complexity : O(N), where N is the size of array.
Auxiliary Space : O(N), where N is the size of array.

We can further reduce the space complexity to O(1).
Since the array will be divided to k sub arrays and all the sub arrays will be continuous. So idea is to calculate the count of sub arrays whose sum is equal to sum of whole array divided by k.
if count == k print Yes else print No.

Following is the implementation for above Approach

## C++

 `// CPP Program to check if array``// can be split into K contiguous``// subarrays each having equal sum``#include ``using` `namespace` `std;` `// function returns true to it is possible to``// create K contiguous partitions each having``// equal sum, otherwise false``int` `KpartitionsPossible(``int` `arr[], ``int` `n, ``int` `k)``{``    ``int` `sum = 0;``    ``int` `count = 0;``    ` `    ``// calculate the sum of the array``    ``for``(``int` `i = 0; i < n; i++)``    ``sum = sum + arr[i];``    ` `    ``if``(sum % k != 0)``    ``return` `0;``    ` `    ``sum = sum / k;``    ``int` `ksum = 0;``    ` `    ``// ksum denotes the sum of each subarray``    ``for``(``int` `i = 0; i < n; i++)``    ``{``    ``ksum=ksum + arr[i];``    ` `    ``// one subarray is found``    ``if``(ksum == sum)``    ``{``        ``// to locate another``        ``ksum = 0;``        ``count++;``    ``}``    ` `    ``}``    ` `    ``if``(count == k)``    ``return` `1;``    ``else``    ``return` `0;``    ` `}` `// Driver code``int` `main() {` `int` `arr[] = { 1, 1, 2, 2};``int` `k = 2;``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``if` `(KpartitionsPossible(arr, n, k) == 0)``        ``cout << ``"Yes"``;``    ``else``        ``cout<<``"No"``;``    ``return` `0;` `}`

## Java

 `//Java Program to check if array``// can be split into K contiguous``// subarrays each having equal sum` `public` `class` `GFG {` `// function returns true to it is possible to``// create K contiguous partitions each having``// equal sum, otherwise false``    ``static` `int` `KpartitionsPossible(``int` `arr[], ``int` `n, ``int` `k) {``        ``int` `sum = ``0``;``        ``int` `count = ``0``;` `        ``// calculate the sum of the array``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``sum = sum + arr[i];``        ``}` `        ``if` `(sum % k != ``0``) {``            ``return` `0``;``        ``}` `        ``sum = sum / k;``        ``int` `ksum = ``0``;` `        ``// ksum denotes the sum of each subarray``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``ksum = ksum + arr[i];` `            ``// one subarray is found``            ``if` `(ksum == sum) {``                ``// to locate another``                ``ksum = ``0``;``                ``count++;``            ``}` `        ``}` `        ``if` `(count == k) {``            ``return` `1``;``        ``} ``else` `{``            ``return` `0``;``        ``}` `    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args) {` `        ``int` `arr[] = {``1``, ``1``, ``2``, ``2``};``        ``int` `k = ``2``;``        ``int` `n = arr.length;` `        ``if` `(KpartitionsPossible(arr, n, k) == ``0``) {``            ``System.out.println(``"Yes"``);``        ``} ``else` `{``            ``System.out.println(``"No"``);``        ``}``    ``}` `}` `/*This code is contributed by PrinciRaj1992*/`

## Python3

 `# Python3 Program to check if array``# can be split into K contiguous``# subarrays each having equal sum` `# Function returns true to it is possible``# to create K contiguous partitions each``# having equal sum, otherwise false``def` `KpartitionsPossible(arr, n, k) :` `    ``sum` `=` `0``    ``count ``=` `0``    ` `    ``# calculate the sum of the array``    ``for` `i ``in` `range``(n) :``        ``sum` `=` `sum` `+` `arr[i]``    ` `    ``if``(``sum` `%` `k !``=` `0``) :``        ``return` `0``    ` `    ``sum` `=` `sum` `/``/` `k``    ``ksum ``=` `0``    ` `    ``# ksum denotes the sum of each subarray``    ``for` `i ``in` `range``(n) :``        ``ksum ``=` `ksum ``+` `arr[i]``    ` `    ``# one subarray is found``    ``if``(ksum ``=``=` `sum``) :``        ` `        ``# to locate another``        ``ksum ``=` `0``        ``count ``+``=` `1``    ` `    ``if``(count ``=``=` `k) :``        ``return` `1``    ``else` `:``        ``return` `0` `# Driver code``if` `__name__ ``=``=` `"__main__"` `:` `    ``arr ``=` `[ ``1``, ``1``, ``2``, ``2``]``    ``k ``=` `2``    ``n ``=` `len``(arr)``    ``if` `(KpartitionsPossible(arr, n, k) ``=``=` `0``) :``        ``print``(``"Yes"``)``    ``else` `:``        ``print``(``"No"``)` `# This code is contributed by Ryuga`

## C#

 `// C# Program to check if array``// can be split into K contiguous``// subarrays each having equal sum` `using` `System;``public` `class` `GFG{`  `// function returns true to it is possible to``// create K contiguous partitions each having``// equal sum, otherwise false``    ``static` `int` `KpartitionsPossible(``int` `[]arr, ``int` `n, ``int` `k) {``        ``int` `sum = 0;``        ``int` `count = 0;` `        ``// calculate the sum of the array``        ``for` `(``int` `i = 0; i < n; i++) {``            ``sum = sum + arr[i];``        ``}` `        ``if` `(sum % k != 0) {``            ``return` `0;``        ``}` `        ``sum = sum / k;``        ``int` `ksum = 0;` `        ``// ksum denotes the sum of each subarray``        ``for` `(``int` `i = 0; i < n; i++) {``            ``ksum = ksum + arr[i];` `            ``// one subarray is found``            ``if` `(ksum == sum) {``                ``// to locate another``                ``ksum = 0;``                ``count++;``            ``}` `        ``}` `        ``if` `(count == k) {``            ``return` `1;``        ``} ``else` `{``            ``return` `0;``        ``}` `    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main() {` `        ``int` `[]arr = {1, 1, 2, 2};``        ``int` `k = 2;``        ``int` `n = arr.Length;` `        ``if` `(KpartitionsPossible(arr, n, k) == 0) {``            ``Console.Write(``"Yes"``);``        ``} ``else` `{``            ``Console.Write(``"No"``);``        ``}``    ``}` `}` `/*This code is contributed by PrinciRaj1992*/`

## PHP

 ``

## Javascript

 ``
Output:
`Yes`

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live

My Personal Notes arrow_drop_up