Check if it possible to partition in k subarrays with equal sum
Last Updated :
07 Mar, 2023
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 :
- For a particular K, each subarray should have a required sum = total_sum / K.
- 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).
- 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.
- 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++
#include <bits/stdc++.h>
using namespace std;
bool KpartitionsPossible( int arr[], int n, int K)
{
int prefix_sum[n];
prefix_sum[0] = arr[0];
for ( int i = 1; i < n; i++)
prefix_sum[i] = prefix_sum[i - 1] + arr[i];
int total_sum = prefix_sum[n-1];
if (total_sum % K != 0)
return false ;
int temp = 0;
int pos = -1;
for ( int i = 0; i < n; i++)
{
if (prefix_sum[i] - (pos == -1 ? 0 :
prefix_sum[pos]) == total_sum / K)
{
pos = i;
temp++;
}
else if (prefix_sum[i] - prefix_sum[pos] >
total_sum / K)
break ;
}
return (temp == K);
}
int main()
{
int arr[] = { 4, 4, 3, 5, 6, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
int K = 3;
if (KpartitionsPossible(arr, n, K))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
public class GfG{
static boolean KpartitionsPossible( int arr[], int n, int K)
{
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];
int total_sum = prefix_sum[n- 1 ];
if (total_sum % K != 0 )
return false ;
int temp = 0 , pos = - 1 ;
for ( int i = 0 ; i < n; i++)
{
if (prefix_sum[i] - (pos == - 1 ? 0 :
prefix_sum[pos]) == total_sum / K)
{
pos = i;
temp++;
}
else if (prefix_sum[i] - (pos == - 1 ? 0 :
prefix_sum[pos]) > total_sum / K)
break ;
}
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" );
}
}
|
Python3
def KpartitionsPossible(arr, n, K):
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]
total_sum = prefix_sum[n - 1 ]
if (total_sum % K ! = 0 ):
return False
temp = 0
pos = - 1
for i in range ( 0 , n, 1 ):
if (pos = = - 1 ):
sub = 0
else :
sub = prefix_sum[pos]
if (prefix_sum[i] - sub = = total_sum / K) :
pos = i
temp + = 1
elif (prefix_sum[i] -
prefix_sum[pos] > total_sum / K):
break
return (temp = = K)
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" )
|
C#
using System;
class GfG
{
static bool KpartitionsPossible( int [] arr, int n, int K)
{
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];
int total_sum = prefix_sum[n-1];
if (total_sum % K != 0)
return false ;
int temp = 0, pos = -1;
for ( int i = 0; i < n; i++)
{
if (prefix_sum[i] - (pos == -1 ? 0 :
prefix_sum[pos]) == total_sum / K)
{
pos = i;
temp++;
}
else if (prefix_sum[i] - (pos == -1 ? 0 :
prefix_sum[pos]) > total_sum / K)
break ;
}
return (temp == K);
}
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" );
}
}
|
PHP
<?php
function KpartitionsPossible( $arr ,
$n , $K )
{
$prefix_sum = Array();
$prefix_sum [0] = $arr [0];
for ( $i = 1; $i < $n ; $i ++)
$prefix_sum [ $i ] = $prefix_sum [ $i - 1] +
$arr [ $i ];
$total_sum = $prefix_sum [ $n - 1];
if ( $total_sum % $K != 0)
return false;
$temp = 0;
$pos = -1;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $prefix_sum [ $i ] - ( $pos == -1 ? 0 :
$prefix_sum [ $pos ]) ==
(int) $total_sum / $K )
{
$pos = $i ;
$temp ++;
}
}
return ( $temp == $K );
}
$arr = array (4, 4, 3,
5, 6, 2);
$n = sizeof( $arr ) ;
$K = 3;
if (KpartitionsPossible( $arr , $n , $K ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function KpartitionsPossible(arr, n, K)
{
let prefix_sum = new Array(n);
prefix_sum[0] = arr[0];
for (let i = 1; i < n; i++)
prefix_sum[i] = prefix_sum[i - 1] +
arr[i];
let total_sum = prefix_sum[n-1];
if (total_sum % K != 0)
return false ;
let temp = 0, pos = -1;
for (let i = 0; i < n; i++)
{
if (prefix_sum[i] - (pos == -1 ? 0 :
prefix_sum[pos]) ==
parseInt(total_sum / K, 10))
{
pos = i;
temp++;
}
else if (prefix_sum[i] - (pos == -1 ? 0 :
prefix_sum[pos]) >
parseInt(total_sum / K, 10))
break ;
}
return (temp == K);
}
let arr = [ 4, 4, 3, 5, 6, 2 ];
let n = arr.length;
let K = 3;
if (KpartitionsPossible(arr, n, K))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
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.
Steps to solve the problem:
- Initialize sum as 0 and count as 0.
- Calculate the sum of all elements in the array arr.
- Check if the sum is divisible by k or not. If not, return 0 as it is not possible to divide the array into k subarrays of equal sum.
- Update the sum as divide the sum by k.
- Initialize ksum as 0.
- Iterate through the array arr and add the current element to ksum.
- If ksum is equal to the target sum, it means that we have found a subarray, so we reset ksum to 0 and increment the count by 1.
- If the count is equal to k, it means that we have successfully divided the array into k subarrays of equal sum, so return 1. Otherwise, return 0.
Following is the implementation for above Approach
C++
#include <bits/stdc++.h>
using namespace std;
int KpartitionsPossible( int arr[], int n, int k)
{
int sum = 0;
int count = 0;
for ( int i = 0; i < n; i++)
sum = sum + arr[i];
if (sum % k != 0)
return 0;
sum = sum / k;
int ksum = 0;
for ( int i = 0; i < n; i++)
{
ksum=ksum + arr[i];
if (ksum == sum)
{
ksum = 0;
count++;
}
}
if (count == k)
return 1;
else
return 0;
}
int main() {
int arr[] = { 1, 1, 2, 2};
int k = 2;
int n = sizeof (arr) / sizeof (arr[0]);
if (KpartitionsPossible(arr, n, k) == 0)
cout << "Yes" ;
else
cout<< "No" ;
return 0;
}
|
Java
public class GFG {
static int KpartitionsPossible( int arr[], int n, int k) {
int sum = 0 ;
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
sum = sum + arr[i];
}
if (sum % k != 0 ) {
return 0 ;
}
sum = sum / k;
int ksum = 0 ;
for ( int i = 0 ; i < n; i++) {
ksum = ksum + arr[i];
if (ksum == sum) {
ksum = 0 ;
count++;
}
}
if (count == k) {
return 1 ;
} else {
return 0 ;
}
}
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" );
}
}
}
|
Python3
def KpartitionsPossible(arr, n, k) :
sum = 0
count = 0
for i in range (n) :
sum = sum + arr[i]
if ( sum % k ! = 0 ) :
return 0
sum = sum / / k
ksum = 0
for i in range (n) :
ksum = ksum + arr[i]
if (ksum = = sum ) :
ksum = 0
count + = 1
if (count = = k) :
return 1
else :
return 0
if __name__ = = "__main__" :
arr = [ 1 , 1 , 2 , 2 ]
k = 2
n = len (arr)
if (KpartitionsPossible(arr, n, k) = = 0 ) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class GFG{
static int KpartitionsPossible( int []arr, int n, int k) {
int sum = 0;
int count = 0;
for ( int i = 0; i < n; i++) {
sum = sum + arr[i];
}
if (sum % k != 0) {
return 0;
}
sum = sum / k;
int ksum = 0;
for ( int i = 0; i < n; i++) {
ksum = ksum + arr[i];
if (ksum == sum) {
ksum = 0;
count++;
}
}
if (count == k) {
return 1;
} else {
return 0;
}
}
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" );
}
}
}
|
PHP
<?php
function KpartitionsPossible( $arr , $n , $k )
{
$sum = 0;
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum = $sum + $arr [ $i ];
if ( $sum % $k != 0)
return 0;
$sum = $sum / $k ;
$ksum = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$ksum = $ksum + $arr [ $i ];
if ( $ksum == $sum )
{
$ksum = 0;
$count ++;
}
}
if ( $count == $k )
return 1;
else
return 0;
}
$arr = array (1, 1, 2, 2);
$k = 2;
$n = count ( $arr );
if (KpartitionsPossible( $arr , $n , $k ) == 0)
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function KpartitionsPossible(arr, n, k)
{
let sum = 0;
let count = 0;
for (let i = 0; i < n; i++)
sum = sum + arr[i];
if (sum % k != 0)
return 0;
sum = parseInt(sum / k, 10);
let ksum = 0;
for (let i = 0; i < n; i++)
{
ksum = ksum + arr[i];
if (ksum == sum)
{
ksum = 0;
count++;
}
}
if (count == k)
return 1;
else
return 0;
}
let arr = [ 1, 1, 2, 2 ];
let k = 2;
let n = arr.length;
if (KpartitionsPossible(arr, n, k) == 0)
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Share your thoughts in the comments
Please Login to comment...