β416. Partition Equal Subset Sum
Medium | Grind 75 | February 26th Sunday, 2023
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.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 100
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.SOLUTION
Calculate the sum of the
numslist.if the sum is odd, return
Falsesince we can't split an odd number into two equal integer parts.Otherwise, continue to step 2
Initialize a
DP, an array of size sum(nums)//2 (HALF) to hold boolean values indicating whether the particular number indicated by the array index can be formed by summing numbers from the nums list. InitializeDP[0]toTruesince the value of zero can always be formed by not adding anything from the nums list.Iterate through the numbers in the
numslist.For every number in the list, iterate from
HALFto thecurrent number - 1to check if thecurrent numbercan form any values fromHALFto thecurrent number-1. We check only until thecurrent number - 1because a number cannot sum to a value smaller than itself.During each iteration(
HALF->current number - 1), updateDPof the currentindexasDP[current index - current number]orDP[current index].DP[current index - current number]takes care of cases where previous numbers from thenumslist summed with the current number can form the current value. Additionally, it takes care of cases where theindexand thecurrent numberare the same.DP[index]ensures the value ofDP[index]remains true if it was previously true andDP[current index - current number]is false
Return the value of
DP[HALF], which indicates whether a subset of numbers in thenumslist can sum up to half of the total sum.
TIME AND SPACE COMPLEXITY
TIME: O(n * m) where n is the length of the nums list and m is half of the sum of the nums list.
SPACE: O(m) where m is half of the sum of the nums list. This is the size of our DP
Last updated