β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 <= 200
1 <= nums[i] <= 100
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
SOLUTION
Calculate the sum of the
nums
list.if the sum is odd, return
False
since 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]
toTrue
since the value of zero can always be formed by not adding anything from the nums list.Iterate through the numbers in the
nums
list.For every number in the list, iterate from
HALF
to thecurrent number - 1
to check if thecurrent number
can form any values fromHALF
to thecurrent number-1
. We check only until thecurrent number - 1
because a number cannot sum to a value smaller than itself.During each iteration(
HALF
->current number - 1
), updateDP
of the currentindex
asDP[current index - current number]
orDP[current index]
.DP[current index - current number]
takes care of cases where previous numbers from thenums
list summed with the current number can form the current value. Additionally, it takes care of cases where theindex
and thecurrent number
are 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 thenums
list can sum up to half of the total sum.
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
# cannot split an odd integer number into equal half
if total % 2: return False
half = total//2
# dp to see what numbers can be summed to using integers in nums list
dp = [False for i in range(half+1)]
dp[0] = True
for number in nums:
for i in range(half, number-1, -1):
dp[i] = dp[i-number] or dp[i]
return dp[half]
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