CodeArchon

medium1-D Dynamic ProgrammingFacebookAmazon

Fair-Share Divider

A sibling arbiter checks whether a bag of marbles can be split into two piles of equal total value.

Given a non-empty array of positive integers, return true iff it can be partitioned into two subsets with equal sum.

Choose approach

1
0
?
1
?
2
?
3
?
4
?
5
?
6
?
7
?
8
?
9
?
10
?
11
i
1/5
Narrationstep 1 of 5

Target = 11. dp[0] = T.

1def canPartition(nums):
2 s = sum(nums)
3 if s % 2: return False
4 t = s // 2
5 dp = [False] * (t + 1); dp[0] = True
6 for n in nums:
7 for a in range(t, n - 1, -1):
8 if dp[a - n]: dp[a] = True
9 return dp[t]
Variables
target=11

How to think about it

  1. Odd total -> impossible.
  2. Classic subset-sum reduction.

Edge cases to catch in interview

  • Single element -> false unless sum == 0.
  • Empty -> trivially true.

Examples

Example 1false
{"nums":[1,2,3,5]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed