Partition Equal Subset Sum
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Can the numbers be split into two groups with the same sum?
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1If the total is odd, can it be split into two equal integers?
- Hint 2Track the set of sums you can reach using some of the numbers so far.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Two siblings sharing a bag of chocolate packets of different sizes, aiming for exactly equal shares. Total odd: impossible. Otherwise you need a handful of packets that adds up to exactly half. Keep a list of every total you can already make. Each new packet gives you new totals: every old total plus the packet. If half-the-total ever appears in the list, the siblings can share fairly.
- The obvious way
Try every subset: O(2^n).
- The key insight
Let half = total / 2 (stop if the total is odd). Keep a set of reachable sums, starting with {0}. For each number add (sum + number) for every reachable sum not above half. Answer: is half reachable?
- The algorithm
- Odd total: False. half = total / 2.
- reachable = {0}.
- For each number add old sum + number to reachable (at most half).
- Return whether half is in reachable.
Watch it run
Examplenums = [1, 5, 11, 5]
Total 22, so each side needs 11. Reachable sums start as {0}.
reachable: 0
Where people slip
- In the array version loop the sums downwards so one packet is not used twice.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def can_partition(nums):
total = sum(nums)
if total % 2 == 1:
return False # cannot be split into two equal whole halves
half = total // 2
reachable = {0} # totals we can make with some of the packets
for packet in nums:
reachable |= {made + packet for made in reachable if made + packet <= half}
return half in reachableNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.