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 Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Length of longest subset consisting of A 0s and B 1s from an array of strings
Next article icon

Partition a Set into Two Subsets of Equal Sum

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.
Note: Each element is present in either the first subset or the second subset, but not in both.

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.

Table of Content

  • [Naive Approach] Using Recursion – O(2^n) Time and O(n) Space
  • [Better Approach 1] Using Top-Down DP (Memoization) – O(sum*n) Time and O(sum*n) Space
  • [Better Approach 2] Using Bottom-Up DP (Tabulation) – O(sum*n) Time and O(sum*n) Space
  • [Expected Approach] Using Space Optimized DP – O(sum*n) Time and O(sum) Space

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

  • Calculate the sum of the array. If the sum is odd, this 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.

[Naive Approach] 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])

Step by Step implementation:

  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 // using recursion  #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 // using recursion  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 # using recursion  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 recursion  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 // using recursion  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 

[Better Approach 1] 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 // using recursion #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 // using top down approach  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 # using top down approach 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 top down approach 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 // using top down approach 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 

[Better Approach 2] 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 // using top up approach  #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 // using top up approach  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 # using top up approach  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 top up approach  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 // using top up approach  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]; } //Driver Code const arr = [1, 5, 11, 5]; if (equalPartition(arr)) {     console.log("True"); } else {     console.log("False"); } 

Output
True 

[Expected Approach] 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 // using space optimised #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 // using space optimised 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 # using space optimised 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 space optimised 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 // using space optimised 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]; }  // Driver code  const arr = [1, 5, 11, 5]; if (equalPartition(arr)) {     console.log("True"); } else {     console.log("False"); } 

Output
True 

Related Articles:

  • Subset Sum Problem
  • Perfect Sum Problem (Print all subsets with given sum)


Next Article
Length of longest subset consisting of A 0s and B 1s from an array of strings
author
kartik
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Accolite
  • Adobe
  • Amazon
  • Drishti-Soft
  • subset
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • Drishti-Soft
  • Dynamic Programming
  • subset

Similar Reads

  • Introduction to Knapsack Problem, its Types and How to solve them
    The Knapsack problem is an example of the combinational optimization problem. This problem is also commonly known as the "Rucksack Problem". The name of the problem is defined from the maximization problem as mentioned below: Given a bag with maximum weight capacity of W and a set of items, each hav
    6 min read
  • Fractional Knapsack

    • Fractional Knapsack Problem
      Given two arrays, val[] and wt[], representing the values and weights of items, and an integer capacity representing the maximum weight a knapsack can hold, the task is to determine the maximum total value that can be achieved by putting items in the knapsack. You are allowed to break items into fra
      8 min read

    • Fractional Knapsack Queries
      Given an integer array, consisting of positive weights "W" and their values "V" respectively as a pair and some queries consisting of an integer 'C' specifying the capacity of the knapsack, find the maximum value of products that can be put in the knapsack if the breaking of items is allowed. Exampl
      9 min read

    • Difference between 0/1 Knapsack problem and Fractional Knapsack problem
      What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large
      13 min read

    0/1 Knapsack

    • 0/1 Knapsack Problem
      Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
      15+ min read

    • Printing Items in 0/1 Knapsack
      Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
      12 min read

    • 0/1 Knapsack Problem to print all possible solutions
      Given weights and profits of N items, put these items in a knapsack of capacity W. The task is to print all possible solutions to the problem in such a way that there are no remaining items left whose weight is less than the remaining capacity of the knapsack. Also, compute the maximum profit.Exampl
      10 min read

    • 0-1 knapsack queries
      Given an integer array W[] consisting of weights of the items and some queries consisting of capacity C of knapsack, for each query find maximum weight we can put in the knapsack. Value of C doesn't exceed a certain integer C_MAX. Examples: Input: W[] = {3, 8, 9} q = {11, 10, 4} Output: 11 9 3 If C
      12 min read

    • 0/1 Knapsack using Branch and Bound
      Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity W. Note: The constraint here is we can either pu
      15+ min read

    • 0/1 Knapsack using Least Cost Branch and Bound
      Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that:   The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations.Examples:   Input:
      15+ min read

  • Unbounded Fractional Knapsack
    Given the weights and values of n items, the task is to put these items in a knapsack of capacity W to get the maximum total value in the knapsack, we can repeatedly put the same item and we can also put a fraction of an item. Examples: Input: val[] = {14, 27, 44, 19}, wt[] = {6, 7, 9, 8}, W = 50 Ou
    5 min read
  • Unbounded Knapsack (Repetition of items allowed)
    Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
    15+ min read
  • Unbounded Knapsack (Repetition of items allowed) | Efficient Approach
    Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W. Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[]
    8 min read
  • Double Knapsack | Dynamic Programming
    Given an array arr[] containing the weight of 'n' distinct items, and two knapsacks that can withstand capactiy1 and capacity2 weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e. an item
    15+ min read
  • Some Problems of Knapsack problem

    • Partition a Set into Two Subsets of Equal Sum
      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.Note: Each element is present in either the first subset or the second subset, but not in both. Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: T
      15+ min read

    • Count of subsets with sum equal to target
      Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. Examples: Input: arr[] = [1, 2, 3, 3], target = 6 Output: 3 Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] Input: arr[] = [1, 1, 1, 1], target = 1
      15+ min read

    • Length of longest subset consisting of A 0s and B 1s from an array of strings
      Given an array arr[] consisting of binary strings, and two integers a and b, the task is to find the length of the longest subset consisting of at most a 0s and b 1s. Examples: Input: arr[] = ["1" ,"0" ,"0001" ,"10" ,"111001"], a = 5, b = 3Output: 4Explanation: One possible way is to select the subs
      15+ min read

    • Breaking an Integer to get Maximum Product
      Given a number n, the task is to break n in such a way that multiplication of its parts is maximized. Input : n = 10Output: 36Explanation: 10 = 4 + 3 + 3 and 4 * 3 * 3 = 36 is the maximum possible product. Input: n = 8Output: 18Explanation: 8 = 2 + 3 + 3 and 2 * 3 * 3 = 18 is the maximum possible pr
      15+ min read

    • Coin Change - Minimum Coins to Make Sum
      Given an array of coins[] of size n and a target value sum, where coins[i] represent the coins of different denominations. You have an infinite supply of each of the coins. The task is to find the minimum number of coins required to make the given value sum. If it is not possible to form the sum usi
      15+ min read

    • Coin Change - Count Ways to Make Sum
      Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
      15+ min read

    • Maximum sum of values of N items in 0-1 Knapsack by reducing weight of at most K items in half
      Given weights and values of N items and the capacity W of the knapsack. Also given that the weight of at most K items can be changed to half of its original weight. The task is to find the maximum sum of values of N items that can be obtained such that the sum of weights of items in knapsack does no
      15+ 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