Distinct Subset Sums With Negatives and Repeated Values
Arrays & HashingModel answerLast updated
List every distinct multiset of array values, each index used at most once, that sums to a target when negatives, zeros and duplicates are present. Output must be sorted.
Distinct Subset Sums With Negatives
You get a list of integers candidates. It may contain repeated values, negative values and zeros. You also get an integer target. Return every distinct combination of values from candidates that adds up to target.
Rules:
- Each element (identified by its position) can be picked at most once per combination.
- Two combinations are the same if they contain the same values with the same multiplicities. Which copy of a repeated value you used does not matter.
- The empty combination is never a valid answer, even when
target = 0. - Sort each combination in non-decreasing order, then sort the list of combinations lexicographically.
def combinationSumWithNegatives(candidates: list[int], target: int) -> list[list[int]]:
...
Constraints
1 <= len(candidates) <= 20-50 <= candidates[i] <= 50-500 <= target <= 500
Examples
Example 1
candidates = [2, -1, 3, -1, 1], target = 2
Output: [[-1, -1, 1, 3], [-1, 1, 2], [-1, 3], [2]]
Sorted, the array is [-1, -1, 1, 2, 3]. The four distinct multisets that hit 2 are -1-1+1+3, -1+1+2, -1+3 and 2. The combination [-1, 3] appears once, even though either -1 could be used.
Example 2
candidates = [-2, 0, 2], target = 0
Output: [[-2, 0, 2], [-2, 2], [0]]
If no combination reaches the target, return [].
What to deliver
Describe and implement an algorithm. Explain:
- Why the usual "stop when the running sum exceeds the target" pruning is unsafe here, and what to use instead.
- How you avoid duplicate combinations.
- The time and space complexity.
- How you would adapt the approach if
ngrew to about 40, or if you only needed the number of distinct combinations.
Hints
Hint 1
Sort first. Equal values become adjacent, so you can decide which copy to use in a canonical way: at a given recursion depth, never start a branch with a value you already tried at that depth.
Hint 2
Because negatives exist, a running sum above the target is not a dead end. Instead, precompute for each suffix the smallest and largest subset sum it can still produce (sum of its negatives, sum of its positives) and prune only when the target is outside that range.
Hint 3
Do not stop recursing when the sum equals the target. Later zeros, or a negative and positive pair, can extend a valid combination into another valid one. Just make sure you do not record the empty path.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the "each element once, no duplicate results" subset-sum enumeration, with two twists: negative numbers break the standard pruning, and zeros mean a valid combination can be extended into another valid one. Backtracking over the sorted array, with two ingredients, handles both.
1. Sort and skip repeated values at the same depth
After sorting, equal values are adjacent. The DFS keeps a start index and tries each i >= start as the next element. If i > start and nums[i] == nums[i-1], that branch would build the same multiset as the branch that used the earlier copy, so we skip it. Deeper levels can still take the second copy, which is how [-1, -1, ...] is produced. Every distinct multiset corresponds to exactly one non-decreasing index path that survives this rule, so the output has no duplicates and misses nothing.
2. Range-based pruning instead of "sum > target"
With negatives, a running total above the target can still fall back down, and one below it can climb back up. So ask a different question: can the target still be reached?
After fixing the choice at index i, the rest of the combination is any subset of nums[i+1:]. Its sum lies between:
neg[i+1], the sum of the negative values in the suffix (the minimum), andpos[i+1], the sum of the positive values in the suffix (the maximum).
Precompute both in one backward pass. With running total ns = s + nums[i]:
- If
ns + neg[i+1] > target, even the most negative completion overshoots. The lower boundnums[i] + neg[i+1]never decreases asiincreases in the sorted array, so every later sibling fails too, and we canbreak. - If
ns + pos[i+1] < target, even the best completion falls short. This bound is not monotone, so we onlycontinue.
3. Record and keep going
Whenever path is non-empty and s == target, store a copy. Then continue recursing. In Example 2, [-2, 2] is valid and extends to [-2, 0, 2], which is also valid. Requiring a non-empty path keeps [] out of the answer when target = 0.
Ordering
Paths are non-decreasing by construction. A pre-order walk over sorted values already tends to emit lexicographic order, but a final res.sort() is cheap and makes the contract explicit.
Code
def combinationSumWithNegatives(candidates: list[int], target: int) -> list[list[int]]:
nums = sorted(candidates)
n = len(nums)
# lo[i] / hi[i]: min / max subset sum achievable using nums[i:]
lo = [0] * (n + 1)
hi = [0] * (n + 1)
for i in range(n - 1, -1, -1):
lo[i] = lo[i + 1] + min(nums[i], 0)
hi[i] = hi[i + 1] + max(nums[i], 0)
res, path = [], []
def dfs(start: int, s: int) -> None:
if path and s == target:
res.append(path[:])
for i in range(start, n):
if i > start and nums[i] == nums[i - 1]:
continue # duplicate branch at this depth
ns = s + nums[i]
if ns + lo[i + 1] > target:
break # monotone: all later siblings fail
if ns + hi[i + 1] < target:
continue # cannot climb back to target
path.append(nums[i])
dfs(i + 1, ns)
path.pop()
dfs(0, 0)
res.sort()
return res
Complexity
- Time: O(n * 2^n) worst case. There can be about 2^n search nodes, and copying a result costs O(n). Pruning helps a lot on typical inputs, but many zeros or a balanced mix of signs defeats it. Sorting and the suffix arrays cost O(n log n).
- Space: O(n) for the recursion stack, path and suffix arrays, plus the output.
Edge cases
- No solution: return
[]. target = 0: exclude the empty set but keep[0],[-2, 2]and similar.- Several zeros:
[0],[0, 0], ... are different multisets and all valid. The skip rule ensures each count appears once. - All same sign: the bounds prune at the root if the target is out of range.
- Single element: works with no special handling.
Common mistakes
- Pruning on
sum > target, which silently drops answers that use later negatives. - Returning right after a match, which loses extensions through zeros or cancelling pairs.
- Writing the skip condition as
nums[i] == nums[i-1]withouti > start, which forbids[-1, -1, ...]. - Hand-checking Example 1 and missing
[-1, 1, 2]. Verify examples against the spec before trusting them. - Forgetting to exclude the empty combination when
target = 0.
Follow-ups
n around 40 (meet in the middle). Enumerating 2^40 subsets is infeasible, but two halves of about 2^20 subsets each are fine. Splitting by index breaks deduplication, because copies of one value can land in both halves. Instead:
- Group values into
(value, count)pairs. - Assign whole groups to a half, balancing the product of
(count + 1). - Enumerate each half's multisets by choosing 0..count copies per group.
- Store the left half in a hash map from sum to multisets.
- For each right multiset, look up
target - its sum.
Every joined pair is a unique multiset, so no extra dedup is needed beyond excluding the empty pair. Listing answers is still output-bound, since the answer itself can be exponential.
Many zeros. With k zeros every non-zero solution has k + 1 variants, and the bounds cannot prune them. Remove the zeros, solve on the rest, then expand each result with 0..k zeros. If target == 0, also add [0]*j for j = 1..k. Re-sort at the end.
Counting only. Every reachable sum lies in [-1000, 1000], so use a DP array with an offset of 1000. Process value groups (v, c) with new[t] = sum over j in 0..c of dp[t - j*v], starting from dp[0] = 1. Read dp[target] and subtract 1 if target == 0 to drop the empty set. That costs roughly O(n * range), about 40,000 operations here.