~/problems / 2-D dynamic programming / Knapsack and coin change

Partition Equal Subset Sum

medium ~20 min

Given a list of positive integers nums, decide whether it can be split into two groups (every element goes into exactly one group) whose sums are equal.

Implement can_partition(nums: list[int]) -> bool.

can_partition([3, 1, 4, 2, 2])  # True   {3, 1, 2} and {4, 2}
can_partition([2, 3, 7])        # False
can_partition([5, 5])           # True

Constraints: 1 <= len(nums) <= 200, 1 <= nums[i] <= 100.

Trying all 2^n subsets is hopeless at n = 200; aim for O(n × sum(nums)).

Show hint

if the two groups have equal sums, what must one group add up to? Rephrase the question as whether some subset reaches that sum.

Topic: Knapsack and coin change. 0/1 vs unbounded; loop order decides combinations vs permutations.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc