Tutorialspoint
Problem
Solution
Submissions

Partition Equal Subset Sum

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to determine if a given non-empty array can be partitioned into two subsets such that the sum of elements in both subsets is equal. This is essentially asking if there exists a subset of the array whose sum is equal to half of the total sum of all elements.

Example 1
  • Input: nums = [1, 5, 11, 5]
  • Output: true
  • Explanation:
    • Total sum = 1 + 5 + 11 + 5 = 22.
    • Half of total sum = 22/2 = 11.
    • We can partition it into [1, 5, 5] and [11].
    • Both subsets have sum = 11, so partition is possible.
Example 2
  • Input: nums = [1, 2, 3, 5]
  • Output: false
  • Explanation:
    • Total sum = 1 + 2 + 3 + 5 = 11.
    • Half of total sum = 11/2 = 5.5 (not an integer).
    • Since half sum is not an integer, equal partition is impossible.
    • Therefore, the array cannot be partitioned into two equal subsets.
Constraints
  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 100
  • The sum of all elements will not exceed 20000
  • Time Complexity: O(n * sum)
  • Space Complexity: O(sum)
ArraysNumberHCL TechnologiesTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • First calculate the total sum of all elements in the array
  • If the total sum is odd, return false immediately as equal partition is impossible
  • Use dynamic programming to check if a subset with sum equal to half of total sum exists
  • Create a boolean DP array where dp[i] represents if sum i is achievable
  • For each number, update the DP array by checking all possible sums
  • Return dp[target] where target is half of the total sum

Steps to solve by this approach:

 Step 1: Calculate the total sum of all elements in the input array.
 Step 2: Check if the total sum is even; if odd, return false as equal partition is impossible.
 Step 3: Set target sum as half of the total sum.
 Step 4: Create a boolean DP array where dp[i] indicates if sum i is achievable using array elements.
 Step 5: Initialize dp[0] as true since sum 0 is always achievable with an empty subset.
 Step 6: For each element, update the DP array by checking all possible sums from target down to the element value.
 Step 7: Return dp[target] which indicates if the target sum (half of total) is achievable.

Submitted Code :