Taro Logo

Partition Equal Subset Sum

#242 Most AskedMedium
1 view
Topics:
Dynamic Programming

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain negative numbers or zeros, or are we guaranteed that all elements are positive integers?
  2. What is the maximum length of the array and the maximum value of the individual elements?
  3. How should we handle an array with an odd total sum, since it's mathematically impossible to split it into two equal integer subsets?
  4. Are duplicate values allowed in the input array, and do they affect the subset partitioning logic?
  5. What should be returned if the input array has fewer than two elements?

Brute Force Solution

Approach

Imagine you are given a collection of items with different weights and you want to know if you can divide them into two groups that weigh exactly the same. The brute force strategy involves testing every single possible way to split the items into two piles to see if any split results in equal weights.

Here's how the algorithm would work step-by-step:

  1. Start by finding the total combined weight of all the items.
  2. If that total weight is an odd number, realize immediately that it is impossible to split them into two equal integer halves, so stop and say no.
  3. If the total weight is an even number, calculate what the target weight for each of the two halves should be, which is half of the total.
  4. Begin exploring all possible combinations of items by picking a few, putting them into a pile, and leaving the rest in another pile.
  5. Calculate the weight of your chosen pile and check if it matches your target weight exactly.
  6. If the weights match, celebrate because you found a valid split and can say yes.
  7. If they do not match, put those items back and try a completely different combination of items.
  8. Repeat this trial-and-error process for every conceivable combination of items until you either find a matching pair of piles or run out of combinations to try.

Code Implementation

def can_partition(nums):    total_weight = sum(nums)        # An odd total weight cannot be split into two equal integer halves    if total_weight % 2 != 0:        return False        target_weight = total_weight // 2        def explore_combinations(current_index, current_sum):        # A match means we successfully found a valid subset equaling our target        if current_sum == target_weight:            return True                # Exceeding the target or running out of elements terminates this path        if current_sum > target_weight or current_index >= len(nums):            return False                include_current = explore_combinations(current_index + 1, current_sum + nums[current_index])        exclude_current = explore_combinations(current_index + 1, current_sum)                return include_current or exclude_current    return explore_combinations(0, 0)

Big(O) Analysis

Time Complexity
O(2^n) – Let n represent the number of items in the collection. The brute force strategy involves testing every conceivable combination of items, which means each item has two choices: either it is included in the pile or it is left out. This explores all 2 to the power of n possible subsets of the items. Summing up the work across these exponential combinations, the total operations approximate a formula of 2^n, which simplifies to the Big O time complexity of O(2^n).
Space Complexity
O(sum) – To keep track of whether specific weights can be formed as we explore combinations of items, we utilize an auxiliary boolean array of size equal to the target weight, which is half of the total sum. As the input elements are processed one by one, this DP table or tracking structure scales with the target value rather than directly with the number of input items N. Therefore, the extra memory required depends on the magnitude of the total sum of the items rather than just N itself.

Optimal Solution

Approach

Instead of checking every possible combination of numbers, the optimal approach focuses on finding out if we can collect a specific target sum. We figure out this target sum by adding all the numbers together and seeing if the total can be split evenly in half.

Here's how the algorithm would work step-by-step:

  1. First, add up all the numbers given to you to find the grand total.
  2. Check if this grand total is an odd number; if it is, you can never split it into two equal whole numbers, so you can immediately stop and say it is impossible.
  3. If the grand total is an even number, divide it by two to find your target sum.
  4. Imagine you have a blank scorecard of possible sums you can make, starting with the score of zero because you can always make zero by choosing nothing.
  5. Look at the first number in your collection and see what new scores you can make by adding this number to the scores already on your scorecard.
  6. Add these newly possible scores to your scorecard.
  7. Repeat this process for every single number in your collection, updating your scorecard with every new possible sum you can reach.
  8. Once you have gone through all the numbers, check your scorecard to see if your target sum is listed as achievable.
  9. If your target sum is on the scorecard, you successfully found a way to split the items equally, meaning the answer is yes.

Code Implementation

def can_partition(number_collection):
    grand_total = sum(number_collection)

    # Odd totals can never be split into two equal integer subsets.
    if grand_total % 2 != 0:
        return False

    target_sum = grand_total // 2
    achievable_scores = {0}

    # Iteratively update achievable sums with each number in the collection.
    for current_number in number_collection:
        new_scores = set()

        for existing_score in achievable_scores:
            new_score = existing_score + current_number
            if new_score <= target_sum:
                new_scores.add(new_score)

        achievable_scores.update(new_scores)

    # Check if the exact half-sum was successfully built.
    if target_sum in achievable_scores:
        return True

    return False

Big(O) Analysis

Time Complexity
O(n * sum) – To analyze the time complexity, let n be the number of elements in the input array and S be the target sum, which is half of the grand total of all numbers. For every single number in the collection, we iterate through all possible sums on our scorecard up to this target sum S. This creates a nested operation where we process n numbers against S possible target values. The total number of operations thus approximates n multiplied by S, which simplifies to the Big O notation of O(n * sum).
Space Complexity
O(sum) – The space complexity is driven by the scorecard of possible sums described in the algorithm, which is implemented as a boolean array or set of size equal to the target sum. Since the target sum is half of the grand total of all numbers, the extra memory required depends on the sum of the elements rather than just the input size N. As we iterate through each of the N numbers in the collection, we update this auxiliary structure in place without needing additional recursive stack frames or large temporary lists. Ultimately, this boils down to an auxiliary space complexity of O(M), where M is the target sum (half of the total sum).

Edge Cases

Array with total sum that is an odd number
How to Handle:
Return false immediately since an odd sum cannot be divided into two equal integer subsets.
Array with a single element
How to Handle:
Return false because a single element cannot be partitioned into two subsets.
Array containing negative numbers
How to Handle:
Standard subset sum DP table assumes positive integers and requires value shifting or constraints validation to handle negative bounds.
Array containing zeros
How to Handle:
Zeros do not change the total sum and are handled naturally by the dynamic programming subset transition logic.
Large array with very large maximum values and sum
How to Handle:
Use a bitset or boolean array optimization to maintain memory efficiency and prevent memory limit exceed errors.
Elements larger than the target subset sum
How to Handle:
Filter or skip any element greater than half of the total sum during the dynamic programming iteration.
All elements are identical
How to Handle:
Check if the count of elements and their values allow an even split of the total sum.
0/257 completed