Partition array to K subsets | Practice | GeeksforGeeks

Given an integer array a[ ] of N elements and an integer K, the task is to check if the array a[ ] could be divided into K non-empty subsets with equal sum of elements.
Note: All elements of this array should be part of exactly one partition.
Example 1:
Input: 
N = 5
a[] = {2,1,4,5,6}
K = 3
Output: 
1
Explanation: we can divide above array 
into 3 parts with equal sum as (2, 4), 
(1, 5), (6)

Example 2:
Input: 
N = 5 
a[] = {2,1,5,5,6}
K = 3
Output: 
0
Explanation: It is not possible to divide
above array into 3 parts with equal sum.

Your Task:
You don't need to read input or print anything. Your task is to complete the function isKPartitionPossible() which takes the array a[], the size of the array N, and the value of K as inputs and returns true(same as 1) if possible, otherwise false(same as 0).
Expected Time Complexity: O(N*2N).
Expected Auxiliary Space: O(2N).
Constraints:
1 ≤ K ≤ N ≤ 10
1 ≤ a[i] ≤ 100
0
ramendramishra1972ra2 weeks ago
c++ soltuion 
 
 
class Solution{ public:  vector<int>v; bool solve (int a[],int n ,int sum,int fixed,int k,vector<bool>&vis ){       //   cout<<"in function"<<"   "<<sum<<endl;                    if(sum==0){k--;             sum=fixed;     }                   if(sum<0){        return false;    }                 for(int i=0;i<n;i++){     if(vis[i]==false&& sum-a[i]>=0){        //   cout<<"considering "<<a[i]<<endl;       //   v.push_back(a[i]);         vis[i]=true;      if(   solve(a,n,sum-a[i],fixed,k,vis)){          return true;      }   //   cout<<"not a viable solution "<<a[i]<<endl;   //   v.pop_back();         vis[i]=false;}              }           if(k==0){         return true;     }     if(k>0){         return false;     } }   bool isKPartitionPossible(int a[], int n, int k)   {       int sum=0;       for(int i=0;i<n;i++){              sum+=a[i];   }   if(sum%k!=0){       return false;   }   if(n<k){       return 0;   }   if(k==1){       return true;   }   // for(auto x:v){   //     cout<<x<<" ";   // }        vector<bool>vis(n,0);      return   solve(a,n,sum/k,sum/k,k,vis);        //Your code here   }};
0
amruthack11012 weeks ago
JAVA 
	class Solution
{
    public boolean isKPartitionPossible(int arr[], int n, int k)
    {	int max=0;
	    if(n<k)return false;
        //Arrays.sort(arr);
        int sum=0;
        if(k==1)
            return true;
        for(int i:arr){
            sum+=i;
            max=Math.max(max,i);
        }
        int val=sum/k;
        if(sum%k!=0||max>val)
            return false;
        boolean[] vis=new boolean[n];
       return canPart(arr,0,k,0,sum/k,vis);
    }
    public boolean canPart(int[] nums,int idx,int k,int sumSF,int tar,boolean []vis)
    {
        if(k==0)return true;
        if(sumSF>tar)return false;
        if(tar==sumSF)
            return canPart(nums,0,k-1,0,tar,vis);
        boolean res=false;
        for(int i=idx;i<nums.length;i++)
        {
            if(vis[i])
                continue;
            vis[i]=true;
            res=res||canPart(nums,i+1,k,sumSF+nums[i],tar,vis);
            vis[i]=false;
        }
        return res;
    }
 }
+2
aaravarya11 month ago
C++ Easy Code Time-Taken(0.0 Sec) Space O(1)
 
  bool isKPartitionPossible(int a[], int n, int k)   {        //Your code here        sort(a,a+n);        int sum=0;         for(int i=0;i<n;i++)        sum+=a[i];                if(sum%k!=0)return false;        sum=sum/k;               for(int i=1;i<=k;i++)        {            int cur=0;            for(int i=n-1; i>=0; i--)            {                if(a[i]+cur<=sum)                {                    cur+=a[i];                    a[i]=0;                }                                if(cur==sum)                break;            }            if(cur<sum)return false;        }       return true;   }};    
0
kuldeepy104591 month ago
bool isKPartitionPossible(int a[], int n, int k)   {        //Your code here        int range=0;        for(int i=0;i<n;i++){            range+=a[i];        }        int sum =range/k;        int x= *max_element(a,a+n);        if(x>sum){            return false;        }        if(range%k!=0){            return false;        }        if(k==1){            return true;        }        else{            bool dp[n+1][sum+1];            for(int j=0;j<=sum;j++){                dp[0][j]=false;            }             for(int j=0;j<=n;j++){                dp[j][0]=true;            }            for(int i=1;i<=n;i++){                for(int j=1;j<=sum;j++){                    dp[i][j]=dp[i-1][j];                    if(j>=a[i-1]){                        dp[i][j]=dp[i][j]||dp[i-1][j-a[i-1]];                    }                }            }            return dp[n][sum];        }           }
0
aditya048481 month ago
# Recursive method

class Solution:
    
    def func(self, arr, dic, curr, curr_sum, req, k):
        if curr_sum == 0:
            k -= 1
            curr_sum = req
            curr = 0
        if k == 0:
            return True
            
        
        res = False
        for i in range(curr, len(arr)):
            
            if i not in dic and curr_sum - arr[i] >= 0:
                dic[i] = True
                res = res or self.func(arr, dic, i, curr_sum-arr[i], req, k)
                dic.pop(i)
                
        return res
    
    
    def isKPartitionPossible(self, a, k):
         
        req = sum(a)/k
        
        if int(req) != req:
            return False
         
        return self.func(a, {}, 0, req, req, k)
    
 
0
aditya048481 month ago
# Time Complexity : O(sum(nums))
def check_req(self,nums,k):
        dp=[[False,-1] for i in range(k+1)]
        dp[0][0]=True
        
        for n,num in enumerate(nums):
            if num!=-1:
                for i in range(k,-1,-1):
                    if not dp[i][0] and i-num>=0 and dp[i-num][0]==True:
                        dp[i][0]=True
                        dp[i][1]=n
        
        if dp[k][0]==True:
            ele=[]
            curr=k
            while curr>0:
                ele.append(dp[curr][1])
                curr-=nums[dp[curr][1]]

            for e in ele:
                nums[e]=-1
    
            return True
                
        else:
            return False
        
    def isKPartitionPossible(self, nums, k):
        
        nums.sort(reverse=True)
        total_sum=sum(nums)
        if total_sum%k!=0:
            return False
        req=total_sum//k
        
        for i in range(k-1):
            if not self.check_req(nums,req):
                return False
            
        return True  
       
0
waky1 month ago
Is this question is lagging some test cases ?
I am able to solve it in 
Time : O(n) and Space: O(1)
 
bool isKPartitionPossible(int a[], int n, int k)
    {
         //Your code here
         int sum = 0;
         for(int i=0;i<n;i++){
             sum += a[i];
         }
         
         if(sum%k!=0)
         return false;
         
         int d = sum/k;
         for(int i=0;i<n;i++){
             if(a[i]>d)
             return false;
         }
         return true;
         
    }
0
joaquin1442 months ago
❌ Why Its answer will be true ?
101 2 3 4 5 6 7 8 9 105
 
We have to make 5 subsets where each have sum 55/5 = 11.
[1,2,3,5] and [4,7]  are 2 possible subsets. We can't get count higher than 2. But we need 5. So answer should be false.
Where I am mistaking ?
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(k*(2^N)) and space complexity as O(2^N) is as follows :- 
 
Execution Time :- 0.0 / 5.8 sec
 
int subsetSum[11];      bool helper(int a[],int n,int ind,int k){       if(ind == n){           for(int i = 1; i < k; i++){               if(subsetSum[i] != subsetSum[i-1]) return (false);           }           return (true);       }              for(int i = 0; i < k; i++){           if(subsetSum[i]){               subsetSum[i] += a[ind];               if(helper(a,n,ind+1,k)){                   return (true);               }               subsetSum[i] -= a[ind];}           else{               subsetSum[i] += a[ind];               if(helper(a,n,ind+1,k)){                   return (true);               }               subsetSum[i] -= a[ind];               break;           }       }              return (false);   }      bool isKPartitionPossible(int a[], int n, int k){       if(k <= 0 || k > n) return (false);       if(k == 1) return (true);              int sum = 0;       for(int i = 0; i < n; i++)           sum += a[i];              if(sum % k) return (false);              for(int i = 0; i < k; i++){           subsetSum[i] = 0;       }       return helper(a,n,0,k);   }
0
nrittik432 months ago
C++ DP solution(Bottom Up)
class Solution{
 public:
   bool isKPartitionPossible(int a[], int n, int k)
   {
        //Your code here
        int range=0; // variable to store the sum of all array elements
        for(int i=0; i<n; ++i) range+=a[i];
        int sum = range/k; // 'sum' here is the target sum for the array
        int* x = max_element(a, a+n);
        if(*x>sum) return false; // largest array element cannot be larger than target sum
        if(range%k!=0) return false; // target sum must be an integer
        if(k==1) return true;
        else{
           int dp[n+1][sum+1]; // can be of bool type
           for(int j=0; j<=sum; ++j){
               dp[0][j]=0;
           }
           for(int i=0; i<=n; ++i){
               dp[i][0]=1;
           }
           // dp logic is similar to equal sum partition problem
           for(int i=1; i<=n; ++i){
               for(int j=1; j<=sum; ++j){
                   if(a[i-1]<=j){
                       if(dp[i-1][j] || dp[i-1][j-a[i-1]]){
                           dp[i][j]=1;
                       }
                       else{
                           dp[i][j]=0;
                       }
                   }
                   else{
                       dp[i][j]=dp[i-1][j];
                   }
               }
           }
           if(dp[n][sum]) return true;
           else return false;
        }
   }
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.