progress

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

Partition Equal Subset Sum

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

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.

⭐ Bonus: a speed test with 199 numbers earns a star in O(n × sum(nums)). Trying all 2^n subsets is hopeless there.

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