KatInterview

Distinct Subset Sums With Negatives and Repeated Values

Arrays & HashingModel answer
HardModel answerArrays & Hashingbacktrackingpruningdeduplication

Last 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:

  1. Why the usual "stop when the running sum exceeds the target" pruning is unsafe here, and what to use instead.
  2. How you avoid duplicate combinations.
  3. The time and space complexity.
  4. How you would adapt the approach if n grew 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.