You get an array nums of positive integers. Decide whether you can split it into two groups with the same sum. Every number goes into exactly one of the two groups.
Return true if such a split exists and false if it does not.
Example 1
Input: nums = [2, 3, 4, 1] Output: true Why: 2 + 3 = 5 and 4 + 1 = 5
2 more examples and the constraints
Example 2
Input: nums = [3, 1, 5] Output: false Why: the sum is 9, and an odd sum cannot be cut in half
Example 3
Input: nums = [1, 2, 5] Output: false Why: the sum is 8, but no group of these numbers adds up to 4
Constraints
- 1 ≤ length of nums ≤ 200
- 1 ≤ nums[i] ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Take or skip, with a memoO(n · S)
- 2D subset-sum tableO(n · S)
- One row, filled right to leftO(n · S)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200 numbers of size 100 | Verdict |
|---|---|---|---|
| Take or skip, with a memo | O(n · S) | Passes; recursion and a big memo | |
| 2D subset-sum table | O(n · S) | Passes; easy to explain | |
| One row, filled right to left | O(n · S) | Best; one array of S + 1 |
n = number of values, S = half the total (at most 10,000).
Edge cases to test
- Odd total. [3, 1, 5] sums to 9: return false before any DP.
- One number. A single positive number can never be split: false.
- Even total, still impossible. [2, 2, 3, 5] sums to 12, but no group makes 6.
- One huge number. [1, 1, 1, 1, 100]: if one value is more than half, there is no split.
Common mistakes
- Looping s from small to large in the one-row version, which lets a number be used more than once.
- Forgetting the odd-total check and then using total / 2 rounded down as the target.
- Starting with dp[0] = false, so no sum can ever be reached.
How to talk through it
- 1Clarify. Must every number be used? Are all values positive? How large can the total get?
- 2Reduce it. Two equal halves means one subset sums to total / 2; an odd total is an instant no.
- 3Give the recursion. Take or skip each number; it is 2ⁿ without a memo, n · S with one.
- 4Squeeze to one row. Build reachable sums bottom up, right to left, so each number counts once.
- 5Test out loud. Run [2, 3, 4, 1], an odd total, and [2, 2, 3, 5].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?