The Wayback Machine - https://web.archive.org/web/20241127060350/https://www.geeksforgeeks.org/partition-problem-dp-18/
Open In App

Partition a Set into Two Subsets of Equal Sum

Last Updated : 15 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.

Examples: 

Input: arr[] = [1, 5, 11, 5]
Output: True 
Explanation: The array can be partitioned as [1, 5, 5] and [11]

Input: arr[] = [1, 5, 3]
Output: False 
Explanation: The array cannot be partitioned into equal sum sets.

Main idea

The following are the two main steps to solve this problem:

  • Calculate the sum of the array. If the sum is odd, there cannot be two subsets with an equal sum, so return false. 
  • If the sum of the array elements is even, calculate sum/2 and find a subset of the array with a sum equal to sum/2. 
    The first step is simple. The second step is crucial, it can be solved either using recursion or Dynamic Programming.

Using Recursion – O(2^n) Time and O(n) Space

Let isSubsetSum(arr, n, sum/2) be the function that returns true if there is a subset of arr[0..n-1] with sum equal to sum/2
The isSubsetSum problem can be divided into two subproblems

  •  isSubsetSum() without considering last element (reducing n to n-1)
  •  isSubsetSum() considering the last element (reducing sum/2 by arr[n-1] and n to n-1)

If any of the above subproblems return true, then return true. 
isSubsetSum (arr, n, sum/2) = isSubsetSum (arr, n-1, sum/2) OR isSubsetSum (arr, n-1, sum/2 – arr[n-1])

Follow the below steps to solve the problem:

  1. First, check if the sum of the elements is even or not.
  2. After checking, call the recursive function isSubsetSum with parameters as input array, array size, and sum/2
    • If the sum is equal to zero then return true (Base case)
    • If n is equal to 0 and sum is not equal to zero then return false (Base case)
    • Check if the value of the last element is greater than the remaining sum then call this function again by removing the last element
    • else call this function again for both the cases stated above and return true, if anyone of them returns true
  3. Print the answer
C++
// C++ program to partition a Set 
// into Two Subsets of Equal Sum
#include <bits/stdc++.h>
using namespace std;

// A utility function that returns true if there is
// a subset of arr[] with sum equal to given sum
bool isSubsetSum(int n, vector<int>& arr, int sum) {
    
    // base cases
    if (sum == 0)
        return true;
    if (n == 0)
        return false;

    // If element is greater than sum, then ignore it
    if (arr[n-1] > sum)
        return isSubsetSum(n-1, arr, sum);

    // Check if sum can be obtained by any of the following
    // (a) including the current element
    // (b) excluding the current element
    return isSubsetSum(n-1, arr, sum) || 
           isSubsetSum(n-1, arr, sum - arr[n-1]);
}

// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
  
    // Calculate sum of the elements in array
    int sum = accumulate(arr.begin(), arr.end(), 0);

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 != 0)
        return false;

    // Find if there is subset with sum equal 
    // to half of total sum
    return isSubsetSum(arr.size(), arr, sum / 2);
}

int main() {
    vector<int> arr = { 1, 5, 11, 5};
    if (equalPartition(arr)) {
        cout << "True" << endl;
    }else{
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to partition a Set 
// into Two Subsets of Equal Sum

class GfG {

    static boolean isSubsetSum(int n, int[] arr, int sum) {
      
        // base cases
        if (sum == 0) 
            return true;
        if (n == 0) 
            return false;

        // If element is greater than sum, then ignore it
        if (arr[n - 1] > sum) 
            return isSubsetSum(n - 1, arr, sum);

        // Check if sum can be obtained by any of the following
        // (a) including the current element
        // (b) excluding the current element
        return isSubsetSum(n - 1, arr, sum) || 
               isSubsetSum(n - 1, arr, sum - arr[n - 1]);
    }

    static boolean equalPartition(int[] arr) {
        
        // Calculate sum of the elements in array
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        // Find if there is subset with sum equal 
        // to half of total sum
        return isSubsetSum(arr.length, arr, sum / 2);
    }

    public static void main(String[] args) {
        int[] arr = { 1, 5, 11, 5 };
        if (equalPartition(arr)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to partition a Set 
# into Two Subsets of Equal Sum

def isSubsetSum(n, arr, sum):
  
    # base cases
    if sum == 0:
        return True
    if n == 0:
        return False

    # If element is greater than sum, then ignore it
    if arr[n-1] > sum:
        return isSubsetSum(n-1, arr, sum)

    # Check if sum can be obtained by any of the following
    # (a) including the current element
    # (b) excluding the current element
    return isSubsetSum(n-1, arr, sum) or \
             isSubsetSum(n-1, arr, sum - arr[n-1])

def equalPartition(arr):
    
    # Calculate sum of the elements in array
    arrSum = sum(arr)

    # If sum is odd, there cannot be two 
    # subsets with equal sum
    if arrSum % 2 != 0:
        return False

    # Find if there is subset with sum equal 
    # to half of total sum
    return isSubsetSum(len(arr), arr, arrSum // 2)

if __name__ == "__main__":
    arr = [1, 5, 11, 5]
    if equalPartition(arr):
        print("True")
    else:
        print("False")
C#
// C# program to partition a Set 
// into Two Subsets of Equal Sum

using System;

class GfG {

    static bool isSubsetSum(int n, int[] arr, int sum) {
      
        // base cases
        if (sum == 0) 
            return true;
        if (n == 0) 
            return false;

        // If element is greater than sum, 
          // then ignore it
        if (arr[n - 1] > sum) 
            return isSubsetSum(n - 1, arr, sum);

        // Check if sum can be obtained by any of the following
        // (a) including the current element
        // (b) excluding the current element
        return isSubsetSum(n - 1, arr, sum) || 
               isSubsetSum(n - 1, arr, sum - arr[n - 1]);
    }

    static bool equalPartition(int[] arr) {
      
        // Calculate sum of the elements in array
        int sum = 0;
        foreach (int num in arr) {
            sum += num;
        }

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        // Find if there is subset with sum equal 
        // to half of total sum
        return isSubsetSum(arr.Length, arr, sum / 2);
    }

    static void Main() {
        int[] arr = { 1, 5, 11, 5 };
        if (equalPartition(arr)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to partition a Set 
// into Two Subsets of Equal Sum

function isSubsetSum(n, arr, sum) {
    
    // base cases
    if (sum == 0) 
        return true;
    if (n == 0) 
        return false;

    // If element is greater than sum, then ignore it
    if (arr[n - 1] > sum) 
        return isSubsetSum(n - 1, arr, sum);

    // Check if sum can be obtained by any of the following
    // (a) including the current element
    // (b) excluding the current element
    return isSubsetSum(n - 1, arr, sum) || 
           isSubsetSum(n - 1, arr, sum - arr[n - 1]);
}

function equalPartition(arr) {
    
    // Calculate sum of the elements in array
    let sum = arr.reduce((a, b) => a + b, 0);

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 !== 0) 
        return false;

    // Find if there is subset with sum equal 
    // to half of total sum
    return isSubsetSum(arr.length, arr, sum / 2);
}

const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Using Top-Down DP (Memoization) – O(sum*n) Time and O(sum*n) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.

1. Optimal Substructure:

The solution to the subset sum problem can be derived from the optimal solutions of smaller subproblems. Specifically, for any given n (the number of elements considered) and a target sum, we can express the recursive relation as follows:

  • If the last element (arr[n-1]) is greater than sum, we cannot include it in our subset isSubsetSum(arr,n,sum) = isSubsetSum(arr,n-1,sum)

If the last element is less than or equal to sum, we have two choices:

  • Include the last element in the subset, isSubsetSum(arr, n, sum) = isSubsetSum(arr, n-1, sum-arr[n-1])
  • Exclude the last element, isSubsetSum(arr, n, sum) = isSubsetSum(arr, n-1, sum)

2. Overlapping Subproblems:

When implementing a recursive approach to solve the subset sum problem, we observe that many subproblems are computed multiple times.

  • The recursive solution involves changing two parameters: the current index in the array (n) and the current target sum (sum). We need to track both parameters, so we create a 2D array of size (n+1) x (sum + 1) because the value of n will be in the range [0, n] and sum will be in the range [0, sum].
  • We initialize the 2D array with -1 to indicate that no subproblems have been computed yet.
  • We check if the value at memo[n][sum] is -1. If it is, we proceed to compute the result. otherwise, we return the stored result.
C++
// C++ program to partition a Set 
// into Two Subsets of Equal Sum
#include <bits/stdc++.h>
using namespace std;

// A utility function that returns true if there is
// a subset of arr[] with sum equal to given sum
bool isSubsetSum(int n, vector<int>& arr, int sum, 
                 vector<vector<int>> &memo) {
    
    // base cases
    if (sum == 0)
        return true;
    if (n == 0)
        return false;
        
    if (memo[n-1][sum]!=-1) return memo[n-1][sum];

    // If element is greater than sum, then ignore it
    if (arr[n-1] > sum)
        return isSubsetSum(n-1, arr, sum, memo);

    // Check if sum can be obtained by any of the following
    // (a) including the current element
    // (b) excluding the current element
    return memo[n-1][sum] = 
            isSubsetSum(n-1, arr, sum, memo) || 
            isSubsetSum(n-1, arr, sum - arr[n-1], memo);
}

// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
  
    // Calculate sum of the elements in array
    int sum = accumulate(arr.begin(), arr.end(), 0);

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 != 0)
        return false;
    
    vector<vector<int>> memo(arr.size(), vector<int>(sum+1, -1));
    
    // Find if there is subset with sum equal 
    // to half of total sum
    return isSubsetSum(arr.size(), arr, sum / 2, memo);
}

int main() {
    vector<int> arr = { 1, 5, 11, 5};
    if (equalPartition(arr)) {
        cout << "True" << endl;
    }else{
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to partition a Set 
// into Two Subsets of Equal Sum
import java.util.Arrays;

class GfG {

    static boolean isSubsetSum(int n, int[] arr,
                               int sum, int[][] memo) {
        // base cases
        if (sum == 0) 
            return true;
        if (n == 0) 
            return false;

        if (memo[n - 1][sum] != -1) 
            return memo[n - 1][sum] == 1;

        // If element is greater than sum, then ignore it
        if (arr[n - 1] > sum) 
            return isSubsetSum(n - 1, arr, sum, memo);

        // Check if sum can be obtained by any of the following
        // (a) including the current element
        // (b) excluding the current element
        memo[n - 1][sum] = (isSubsetSum(n - 1, arr, sum, memo) || 
                            isSubsetSum(n - 1, arr, sum - arr[n - 1], memo)) ? 1 : 0;
        return memo[n - 1][sum] == 1;
    }

    static boolean equalPartition(int[] arr) {
      
        // Calculate sum of the elements in array
        int sum = 0;
        for (int num : arr) {
            sum += num;
        }

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        int[][] memo = new int[arr.length][sum + 1];
        for (int[] row : memo) {
            Arrays.fill(row, -1);
        }

        // Find if there is subset with sum equal 
        // to half of total sum
        return isSubsetSum(arr.length, arr, sum / 2, memo);
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 11, 5};
        if (equalPartition(arr)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to partition a Set 
# into Two Subsets of Equal Sum

def isSubsetSum(n, arr, sum, memo):
    
    # base cases
    if sum == 0:
        return True
    if n == 0:
        return False

    if memo[n-1][sum] != -1:
        return memo[n-1][sum]

    # If element is greater than sum, then ignore it
    if arr[n-1] > sum:
        return isSubsetSum(n-1, arr, sum, memo)

    # Check if sum can be obtained by any of the following
    # (a) including the current element
    # (b) excluding the current element
    memo[n-1][sum] = isSubsetSum(n-1, arr, sum, memo) or\
                     isSubsetSum(n-1, arr, sum - arr[n-1], memo)
    return memo[n-1][sum]

def equalPartition(arr):
    
    # Calculate sum of the elements in array
    arrSum = sum(arr)

    # If sum is odd, there cannot be two 
    # subsets with equal sum
    if arrSum % 2 != 0:
        return False

    memo = [[-1 for _ in range(arrSum+1)] for _ in range(len(arr))]
    
    # Find if there is subset with sum equal 
    # to half of total sum
    return isSubsetSum(len(arr), arr, arrSum // 2, memo)

if __name__ == "__main__":
    arr = [1, 5, 11, 5]
    if equalPartition(arr):
        print("True")
    else:
        print("False")
C#
// C# program to partition a Set 
// into Two Subsets of Equal Sum

using System;

class GfG {

    static bool isSubsetSum(int n, int[] arr, int sum,
                            int[,] memo) {
        
        // base cases
        if (sum == 0) 
            return true;
        if (n == 0) 
            return false;

        if (memo[n - 1, sum] != -1) 
            return memo[n - 1, sum] == 1;

        // If element is greater than sum, then ignore it
        if (arr[n - 1] > sum) 
            return isSubsetSum(n - 1, arr, sum, memo);

        // Check if sum can be obtained by any of the following
        // (a) including the current element
        // (b) excluding the current element
        memo[n - 1, sum] = (isSubsetSum(n - 1, arr, sum, memo) || 
                            isSubsetSum(n - 1, arr, sum - arr[n - 1], memo)) ? 1 : 0;
        return memo[n - 1, sum] == 1;
    }

    static bool equalPartition(int[] arr) {
        
        // Calculate sum of the elements in array
        int sum = 0;
        foreach (int num in arr) {
            sum += num;
        }

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        int[,] memo = new int[arr.Length, sum + 1];
        for (int i = 0; i < arr.Length; i++) {
            for (int j = 0; j <= sum; j++) {
                memo[i, j] = -1;
            }
        }

        // Find if there is subset with sum equal 
        // to half of total sum
        return isSubsetSum(arr.Length, arr, sum / 2, memo);
    }

    static void Main() {
        int[] arr = { 1, 5, 11, 5 };
        if (equalPartition(arr)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to partition a Set 
// into Two Subsets of Equal Sum

function isSubsetSum(n, arr, sum, memo) {
    
    // base cases
    if (sum == 0) 
        return true;
    if (n == 0) 
        return false;

    if (memo[n - 1][sum] !== -1) 
        return memo[n - 1][sum];

    // If element is greater than sum, then ignore it
    if (arr[n - 1] > sum) 
        return isSubsetSum(n - 1, arr, sum, memo);

    // Check if sum can be obtained by any of the following
    // (a) including the current element
    // (b) excluding the current element
    memo[n - 1][sum] = isSubsetSum(n - 1, arr, sum, memo) || 
                       isSubsetSum(n - 1, arr, sum - arr[n - 1], memo);
    return memo[n - 1][sum];
}

function equalPartition(arr) {
    
    // Calculate sum of the elements in array
    let sum = arr.reduce((a, b) => a + b, 0);

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 !== 0) 
        return false;

    let memo = Array.from(Array(arr.length), () => Array(sum + 1).fill(-1));

    // Find if there is subset with sum equal 
    // to half of total sum
    return isSubsetSum(arr.length, arr, sum / 2, memo);
}

const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Using Bottom-Up DP (Tabulation) – O(sum*n) Time and O(sum*n) Space

The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.

So we will create a 2D array of size (n + 1) * (sum + 1) of type boolean. The state dp[i][j] will be true if there exists a subset of elements from arr[0 . . . i] with sum = ‘j’. 

The dynamic programming relation is as follows: 

if (arr[i-1] > j)
    dp[i][j] = dp[i-1][j]
else 
    dp[i][j] = dp[i-1][j] OR dp[i-1][j-arr[i-1]]

This means that if the current element has a value greater than the ‘current sum value’ we will copy the answer for previous cases and if the current sum value is greater than the ‘ith’ element we will see if any of the previous states have already computed the sum = j OR any previous states computed a value ‘j – arr[i]’ which will solve our purpose.

C++
// C++ program to partition a Set 
// into Two Subsets of Equal Sum
#include <bits/stdc++.h>
using namespace std;

// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
  
    // Calculate sum of the elements in array
    int sum = accumulate(arr.begin(), arr.end(), 0);
    int n = arr.size();

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 != 0)
        return false;
        
    sum = sum/2;
    
    // Create a 2D vector for storing results
    // of subproblems
    vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1, false));

    // If sum is 0, then answer is true (empty subset)
    for (int i = 0; i <= n; i++)
        dp[i][0] = true;

    // Fill the dp table in bottom-up manner
    for (int i = 1; i <= n; i++) {
      
        for (int j = 1; j <= sum; j++) {
            if (j < arr[i - 1]) {
              
                // Exclude the current element
                dp[i][j] = dp[i - 1][j]; 
            }
            else {
              
                // Include or exclude
                dp[i][j] = dp[i - 1][j] 
                || dp[i - 1][j - arr[i - 1]];
            }
        }
    }

    return dp[n][sum];
}

int main() {
    vector<int> arr = { 1, 5, 11, 5};
    if (equalPartition(arr)) {
        cout << "True" << endl;
    }else{
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to partition a Set 
// into Two Subsets of Equal Sum

class GfG {

    static boolean equalPartition(int[] arr) {
        
        // Calculate sum of the elements in array
        int sum = 0;
        for (int num : arr) {
            sum += num;
        }
        int n = arr.length;

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        sum = sum / 2;

        // Create a 2D array for storing results
        // of subproblems
        boolean[][] dp = new boolean[n + 1][sum + 1];

        // If sum is 0, then answer is true (empty subset)
        for (int i = 0; i <= n; i++) {
            dp[i][0] = true;
        }

        // Fill the dp table in bottom-up manner
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
                if (j < arr[i - 1]) {
                  
                    // Exclude the current element
                    dp[i][j] = dp[i - 1][j];
                } else {
                  
                    // Include or exclude
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - arr[i - 1]];
                }
            }
        }

        return dp[n][sum];
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 11, 5};
        if (equalPartition(arr)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to partition a Set 
# into Two Subsets of Equal Sum

def equalPartition(arr):
    
    # Calculate sum of the elements in array
    arrSum = sum(arr)
    n = len(arr)

    # If sum is odd, there cannot be two 
    # subsets with equal sum
    if arrSum % 2 != 0:
        return False

    arrSum = arrSum // 2

    # Create a 2D array for storing results
    # of subproblems
    dp = [[False] * (arrSum + 1) for _ in range(n + 1)]

    # If sum is 0, then answer is true (empty subset)
    for i in range(n + 1):
        dp[i][0] = True

    # Fill the dp table in bottom-up manner
    for i in range(1, n + 1):
        for j in range(1, arrSum + 1):
            if j < arr[i - 1]:
              
                # Exclude the current element
                dp[i][j] = dp[i - 1][j]
            else:
              
                # Include or exclude
                dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]

    return dp[n][arrSum]

if __name__ == "__main__":
    arr = [1, 5, 11, 5]
    if equalPartition(arr):
        print("True")
    else:
        print("False")
C#
// C# program to partition a Set 
// into Two Subsets of Equal Sum

using System;

class GfG {

    static bool equalPartition(int[] arr) {
        
        // Calculate sum of the elements in array
        int sum = 0;
        foreach (int num in arr) {
            sum += num;
        }
        int n = arr.Length;

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        sum = sum / 2;

        // Create a 2D array for storing results
        // of subproblems
        bool[,] dp = new bool[n + 1, sum + 1];

        // If sum is 0, then answer is true (empty subset)
        for (int i = 0; i <= n; i++) {
            dp[i, 0] = true;
        }

        // Fill the dp table in bottom-up manner
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
                if (j < arr[i - 1]) {
                  
                    // Exclude the current element
                    dp[i, j] = dp[i - 1, j];
                } else {
                  
                    // Include or exclude
                    dp[i, j] = dp[i - 1, j] || dp[i - 1, j - arr[i - 1]];
                }
            }
        }

        return dp[n, sum];
    }

    static void Main() {
        int[] arr = { 1, 5, 11, 5 };
        if (equalPartition(arr)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to partition a Set 
// into Two Subsets of Equal Sum

function equalPartition(arr) {
    
    // Calculate sum of the elements in array
    let sum = arr.reduce((a, b) => a + b, 0);
    let n = arr.length;

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 !== 0) 
        return false;

    sum = sum / 2;

    // Create a 2D array for storing results
    // of subproblems
    let dp = Array.from({ length: n + 1 }, () => Array(sum + 1).fill(false));

    // If sum is 0, then answer is true (empty subset)
    for (let i = 0; i <= n; i++) {
        dp[i][0] = true;
    }

    // Fill the dp table in bottom-up manner
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= sum; j++) {
            if (j < arr[i - 1]) {
            
                // Exclude the current element
                dp[i][j] = dp[i - 1][j];
            } else {
            
                // Include or exclude
                dp[i][j] = dp[i - 1][j] || dp[i - 1][j - arr[i - 1]];
            }
        }
    }

    return dp[n][sum];
}

const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

The following diagram shows the values in the partition table:

Using Space Optimized DP – O(sum*n) Time and O(sum) Space

In previous approach of dynamic programming we have derive the relation between states as given below:

if (arr[i-1] > j)
    dp[i][j] = dp[i-1][j]
else 
    dp[i][j] = dp[i-1][j] OR dp[i-1][j-arr[i-1]]

If we observe that for calculating current dp[i][j] state we only need previous row dp[i-1][j] or dp[i-1][j-arr[i-1]]. There is no need to store all the previous states just one previous state is used to compute result.

Approach:

  • Define two arrays prev and curr of size sum+1 to store the just previous row result and current row result respectively.
  • Once curr array is calculated then curr becomes our prev for the next row.
  • When all rows are processed the answer is stored in prev array.
C++
// C++ program to partition a Set 
// into Two Subsets of Equal Sum
#include <bits/stdc++.h>
using namespace std;

// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
  
    // Calculate sum of the elements in array
    int sum = accumulate(arr.begin(), arr.end(), 0);
    
    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 != 0) 
        return false;

    sum = sum / 2;
    
    int n = arr.size();
    vector<bool> prev(sum + 1, false), curr(sum + 1);

    // Mark prev[0] = true as it is true
    // to make sum = 0 using 0 elements
    prev[0] = true;

    // Fill the subset table in
    // bottom up manner
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j <= sum; j++) {
            if (j < arr[i - 1])
                curr[j] = prev[j];
            else
                curr[j] = (prev[j] || prev[j - arr[i - 1]]);
        }
        prev = curr;
    }
    return prev[sum];
}

int main() {
    vector<int> arr = { 1, 5, 11, 5};
    if (equalPartition(arr)) {
        cout << "True" << endl;
    }else{
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to partition a Set 
// into Two Subsets of Equal Sum

class GfG {

    static boolean equalPartition(int[] arr) {
        
        // Calculate sum of the elements in array 
        int sum = 0; 
        for (int num : arr) {
            sum += num;
        }
        
        // If sum is odd, there cannot be two 
        // subsets with equal sum 
        if (sum % 2 != 0)
            return false;

        sum = sum / 2;

        int n = arr.length;
        boolean[] prev = new boolean[sum + 1];
        boolean[] curr = new boolean[sum + 1];

        // Mark prev[0] = true as it is true
        // to make sum = 0 using 0 elements
        prev[0] = true;

        // Fill the subset table in
        // bottom-up manner
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                if (j < arr[i - 1])
                    curr[j] = prev[j];
                else
                    curr[j] = (prev[j] || prev[j - arr[i - 1]]);
            }
            
            // copy curr into prev 
            for (int j=0; j<=sum; j++) {
                prev[j] = curr[j];
            }
        }
        return prev[sum];
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 11, 5};
        if (equalPartition(arr)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to partition a Set 
# into Two Subsets of Equal Sum

def equalPartition(arr):
  
    # Calculate sum of the elements in array
    arrSum = sum(arr)

    # If sum is odd, there cannot be two 
    # subsets with equal sum
    if arrSum % 2 != 0:
        return False

    arrSum = arrSum // 2

    n = len(arr)
    prev = [False] * (arrSum + 1)
    curr = [False] * (arrSum + 1)

    # Mark prev[0] = true as it is true
    # to make sum = 0 using 0 elements
    prev[0] = True

    # Fill the subset table in
    # bottom-up manner
    for i in range(1, n + 1):
        for j in range(arrSum + 1):
            if j < arr[i - 1]:
                curr[j] = prev[j]
            else:
                curr[j] = (prev[j] or prev[j - arr[i - 1]])

        prev = curr.copy()

    return prev[arrSum]

if __name__ == "__main__":
    arr = [1, 5, 11, 5]
    if equalPartition(arr):
        print("True")
    else:
        print("False")
C#
// C# program to partition a Set 
// into Two Subsets of Equal Sum

using System;

class GfG {

    static bool equalPartition(int[] arr) {
        
        // Calculate sum of the elements in array
        int sum = 0;
        foreach (int num in arr) {
            sum += num;
        }

        // If sum is odd, there cannot be two 
        // subsets with equal sum
        if (sum % 2 != 0) 
            return false;

        sum = sum / 2;

        int n = arr.Length;
        bool[] prev = new bool[sum + 1];
        bool[] curr = new bool[sum + 1];

        // Mark prev[0] = true as it is true
        // to make sum = 0 using 0 elements
        prev[0] = true;

        // Fill the subset table in
        // bottom-up manner
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                if (j < arr[i - 1])
                    curr[j] = prev[j];
                else
                    curr[j] = (prev[j] || prev[j - arr[i - 1]]);
            }
            
            prev = (bool[])curr.Clone();
        }

        return prev[sum];
    }

    static void Main() {
        int[] arr = { 1, 5, 11, 5 };
        if (equalPartition(arr)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to partition a Set 
// into Two Subsets of Equal Sum

function equalPartition(arr) {
    
    // Calculate sum of the elements in array
    let sum = arr.reduce((a, b) => a + b, 0);

    // If sum is odd, there cannot be two 
    // subsets with equal sum
    if (sum % 2 !== 0) 
        return false;

    sum = sum / 2;

    let n = arr.length;
    let prev = Array(sum + 1).fill(false);
    let curr = Array(sum + 1).fill(false);

    // Mark prev[0] = true as it is true
    // to make sum = 0 using 0 elements
    prev[0] = true;

    // Fill the subset table in
    // bottom-up manner
    for (let i = 1; i <= n; i++) {
        for (let j = 0; j <= sum; j++) {
            if (j < arr[i - 1]) {
                curr[j] = prev[j];
            } else {
                curr[j] = (prev[j] || prev[j - arr[i - 1]]);
            }
        }
        prev = [...curr];
    }

    return prev[sum];
}

const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Related Articles:



Previous Article
Next Article

Similar Reads

Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first subset is minimum. If there is still a tie then p
14 min read
Partition of a set into K subsets with equal sum
Given an integer array of N elements, the task is to divide this array into K non-empty subsets such that the sum of elements in every subset is same. All elements of this array should be part of exactly one partition. Examples: Input : arr = [2, 1, 4, 5, 6], K = 3 Output : Yes we can divide above array into 3 parts with equal sum as [[2, 4], [1, 5
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 the given array are [2, 4], [1, 5] and [6] Input:
9 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 partition, then print "-1". Examples: Input: arr[]
13 min read
Closest sum partition (into two subsets) of numbers from 1 to n
Given an integer sequence 1, 2, 3, 4, ..., n. The task is to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is the minimum possible. Print the value of |sum(A) - sum(B)|. Examples: Input: 3 Output: 0 A = {1, 2} and B = {3} ans |sum(A) - sum(B)| = |3 - 3| = 0. Input: 6 Output: 0 A = {
4 min read
Partition a set into two non-empty subsets such that the difference of subset sums is maximum
Given a set of integers S, the task is to divide the given set into two non-empty sets S1 and S2 such that the absolute difference between their sums is maximum, i.e., abs(sum(S1) – sum(S2)) is maximum. Example: Input: S[] = { 1, 2, 1 } Output: 2Explanation:The subsets are {1} and {2, 1}. Their absolute difference is abs(1 - (2+1)) = 2, which is ma
7 min read
Partition a set into two subsets such that the difference of subset sums is minimum
Given an array arr[] of size n, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) - sum(Subset2)) should be minimum. Example: Input: arr = [1,
15+ min read
Partition array into minimum number of equal length subsets consisting of a single distinct value
Given an array arr[] of size N, the task is to print the minimum count of equal length subsets the array can be partitioned into such that each subset contains only a single distinct element Examples: Input: arr[] = { 1, 2, 3, 4, 4, 3, 2, 1 } Output: 4 Explanation: Possible partition of the array is { {1, 1}, {2, 2}, {3, 3}, {4, 4} }. Therefore, th
6 min read
Partition into two subsets of lengths K and (N - k) such that the difference of sums is maximum
Given an array of non-negative integers of length N and an integer K. Partition the given array into two subsets of length K and N - K so that the difference between the sum of both subsets is maximum. Examples : Input : arr[] = {8, 4, 5, 2, 10} k = 2 Output : 17 Explanation : Here, we can make first subset of length k = {4, 2} and second subset of
7 min read
Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum
Given an array arr[] of size N, the task is to split the array into two subsets such that the Bitwise XOR between the maximum of the first subset and minimum of the second subset is minimum. Examples: Input: arr[] = {3, 1, 2, 6, 4} Output: 1 Explanation: Splitting the given array in two subsets {1, 3}, {2, 4, 6}. The maximum of the first subset is
5 min read
Count number of ways to partition a set into k subsets
Given two numbers n and k where n represents a number of elements in a set, find a number of ways to partition the set into k subsets.Example: Input: n = 3, k = 2Output: 3Explanation: Let the set be [1, 2, 3], we can partition it into 3 subsets in the following ways [[1,2], [3]], [[1], [2,3]], [[1,3], [2]]. Input: n = 3, k = 1Output: 1Explanation:
15+ min read
Divide array in two Subsets such that sum of square of sum of both subsets is maximum
Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pairs are as follows (1)2 + (2 + 3)2 = 26 (2)2 + (1
6 min read
Partition Array into two Arrays of equal size to Minimize Sum Difference
Given an integer array of size 2*n, partition the array into two arrays of equal length such that the absolute difference between the sums of these two arrays is minimum. Return this minimum difference. To partition the array, allocate each element to one of two arrays. Examples :Input: arr[] = {7, 3, 2, 8} Output: 0Explanation :Subset1 = {2, 8}, s
15+ min read
Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
Given an array A[] consisting of N integers, the task is to split the array A[] into subsets having equal sum and of length equal to elements in array B[]. Examples: Input: A[] = {17, 13, 21, 20, 50, 29}, B[] = {2, 3, 1} Output: 21 29 17 13 20 50 Input: A[] = { 1, 2, 3, 4, 5, 6}, B[] = { 2, 2, 2} Output: 1 6 2 5 3 4 Approach: Follow the steps below
8 min read
Partition into minimum subsets (or subsequences) with consecutive
Given an array of distinct positive numbers, the task is to partition the array into the number of subsets (or subsequences) such that each subset contains consecutive numbers. Examples: Input : arr[] = {100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59}Output : 3{5, 6, 7}, { 56, 57, 58, 59}, {100, 101, 102, 103} are 3 subset in which numbers are consecu
7 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 split into {2, 5} and {3, 4} Input: Arr[] = {1, 2,
15+ min read
Split numbers from 1 to N into two equal sum subsets
Given an integer N, the task is to divide the numbers from 1 to N into two nonempty subsets such that the sum of elements in the set is equal. Print the element in the subset. If we can't form any subset then print -1. Examples: Input N = 4 Output: Size of subset 1 is: 2 Elements of the subset are: 1 4 Size of subset 2 is: 2 Elements of the subset
10 min read
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once
Given an array arr[] consisting of N distinct integers, the task is to find the minimum number of times the array needs to be split into two subsets such that elements of each pair are present into two different subsets at least once. Examples: Input: arr[] = { 3, 4, 2, 1, 5 } Output: 3 Explanation: Possible pairs are { (1, 2), (1, 3), (1, 4), (1,
6 min read
Maximum number of subsets an array can be split into such that product of their minimums with size of subsets is at least K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of disjoint subsets that the given array can be split into such that the product of the minimum element of each subset with the size of the subset is at least K. Examples: Input: arr[] = {7, 11, 2, 9, 5}, K = 10Output: 2Explanation:All such disjoi
8 min read
Partition the array into three equal sum segments
Given an array of n integers, we have to partition the array into three segments such that all the segments have an equal sum. Segment sum is the sum of all the elements in the segment. Examples: Input : 1, 3, 6, 2, 7, 1, 2, 8 Output : [1, 3, 6], [2, 7, 1], [2, 8] Input : 7, 6, 1, 7 Output : [7], [6, 1], [7] Input : 7, 6, 2, 7 Output : Cannot divid
12 min read
Split array into two equal length subsets such that all repetitions of a number lies in a single subset
Given an array arr[] consisting of N integers, the task is to check if it is possible to split the integers into two equal length subsets such that all repetitions of any array element belong to the same subset. If found to be true, print "Yes". Otherwise, print "No". Examples: Input: arr[] = {2, 1, 2, 3}Output: YesExplanation:One possible way of d
15+ min read
Partition first N natural number into two sets such that their sum is not coprime
Given an integer N, the task is to partition the first N natural numbers in two non-empty sets such that the sum of these sets is not coprime to each other. If it is possible then find the possible partition then print -1 else print the sum of elements of both sets.Examples: Input: N = 5 Output: 10 5 {1, 2, 3, 4} and {5} are the valid partitions.In
4 min read
Divide first N natural numbers into 3 equal sum subsets
Given an integer N, the task is to check whether the elements from the range [1, N] can be divided into three non-empty equal sum subsets. If possible then print Yes else print No. Examples: Input: N = 5 Output: Yes The possible subsets are {1, 4}, {2, 3} and {5}. (1 + 4) = (2 + 3) = (5) Input: N = 3 Output: No Approach: There are two cases: If N ?
5 min read
Split array into equal length subsets with maximum sum of Kth largest element of each subset
Given an array arr[] of size N, two positive integers M and K, the task is to partition the array into M equal length subsets such that the sum of the Kth largest element of all these subsets is maximum. If it is not possible to partition the array into M equal length subsets, then print -1. Examples: Input: arr[] = { 1, 2, 3, 4, 5, 6 }, M = 2, K =
7 min read
Count ways to split array into pair of subsets with difference between their sum equal to K
Given an array arr[] consisting of N integers and an integer K, the task is to find the number of ways to split the array into a pair of subsets such that the difference between their sum is K. Examples: Input: arr[] = {1, 1, 2, 3}, K = 1Output: 3Explanation:Following splits into a pair of subsets satisfies the given condition: {1, 1, 2}, {3}, diff
15 min read
Sum of subsets of all the subsets of an array | O(3^N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
6 min read
Sum of subsets of all the subsets of an array | O(2^N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
6 min read
Sum of subsets of all the subsets of an array | O(N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
7 min read
Print equal sum sets of array (Partition problem) | Set 1
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Inpu
14 min read
Split N powers of 2 into two subsets such that their difference of sum is minimum
Given an even number N, the task is to split all N powers of 2 into two sets such that the difference of their sum is minimum.Examples: Input: n = 4 Output: 6 Explanation: Here n = 4 which means we have 21, 22, 23, 24. The most optimal way to divide it into two groups with equal element is 24 + 21 in one group and 22 + 23 in another group giving a
6 min read
three90RightbarBannerImg