Skip to content
mlmentorship

Combination Sum IV

Partition ordered sequences by their final value, distinguish total-first from denomination-first counting, and add a length bound before allowing nonpositive values.

Published · 15 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Combination Sum IV

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list nums of distinct positive integers and a nonnegative integer target. Output. Return the number of ordered value sequences whose sum equals target. Rules. A value may be reused any number of times; different orders count separately. Target zero has one sequence: the empty sequence. An unreachable positive target has zero sequences. Leave the input unchanged. The reference neither validates positivity nor removes duplicate input values. Example. For nums = [1, 2] and target = 3, return 3. The sequences are [1, 1, 1], [1, 2], and [2, 1].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Build ways[total] by choosing each eligible final number and adding ways[total - number].

Problem trace

Group ordered sequences by their last number, then add their counts

Worked example: group ordered sequences by their last valueWith values (1,2) and target 4, group by last value. Three sequences end in 1; two end in 2.Sort all 5 paths by their disjointfinal move1111last 1121last 1211last 1112last 222last 23 end in one; 2 end in two. Everypath sums to 4.
Read it this way: With values (1,2) and target 4, group by last value. Three sequences end in 1; two end in 2. Do 1,1,2 and 2,1,1 belong to the same final-value group?
Full interview answer 15 min read

Count the ordered sequences of available positive values that add to an exact target.

Problem

Input. A list nums of distinct positive integers and a nonnegative integer target.

Output. Return the number of ordered value sequences whose sum equals target.

Rules. A value may be reused any number of times; different orders count separately. Target zero has one sequence: the empty sequence. An unreachable positive target has zero sequences. Leave the input unchanged. The reference neither validates positivity nor removes duplicate input values.

Example. For nums = [1, 2] and target = 3, return 3. The sequences are [1, 1, 1], [1, 2], and [2, 1].

Picture

For values [1,2,3] and target four:

Final valuePrefix totalPrefix countExample
134[3,1]
222[2,2]
311[1,3]

The result is . [1,3] and [3,1] belong to different groups and are different sequences.

Reuse the disjoint predecessor-count rule. The base ways[0]=1 counts one empty sequence. It lets a final value form a one-element sequence without a special case.

Before processing total, every smaller total is final. The update adds ways[total-num] for each allowed final value. Positive values make every dependency smaller; distinct values prevent counting a final group twice.

Keep totals outside choices so every ordered prefix is available. Combination Sum instead treats reordered values as one answer. For this example, unordered counting gives four, not seven.

Nodes below show total:ways. Each lower node contributes its count for the labeled final value.

Target zero returns one, including when values are empty. Positive targets with no values return zero. Zero creates self-dependence; negative values can index future or nonexistent slots. Neither belongs in this recurrence unchanged.

Problem trace

Separate fixture: count ordered sequences with the code's full move set

Input and goalCount ordered sequences of values that add to the target.
Initialize the empty sequenceFor values [1,2,3], ways[0]=1 counts the empty sequence. All positive totals start at zero.
0:1
base1001020304
indicestotal 0..4
base
0
indices
total 0..4
index 0
1

Recognize it
Use it when order matters, values may be reused, and every sequence reaching a total has one unambiguous final value that reduces it to a smaller solved total.
Keep true
Before processing total t, ways[0..t-1] contain exact ordered-sequence counts; after trying every num <= t, ways[t] counts each sequence exactly once by its final number.
Reuse it
To count ordered constructions, partition answers by the last decision and iterate states before choices; changing loop order can change the combinatorial object being counted.
For values [1,2,3], ways[0]=1 counts the empty sequence. All positive totals start at zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why are [1,3] and [3,1] counted separately without double-counting either sequence?
Reference drawing

Problem trace

Group ordered sequences by their last number, then add their counts

Worked example: group ordered sequences by their last valueWith values (1,2) and target 4, group by last value. Three sequences end in 1; two end in 2.Sort all 5 paths by their disjointfinal move1111last 1121last 1211last 1112last 222last 23 end in one; 2 end in two. Everypath sums to 4.
Execution trace
Input and goalCount ordered sequences of values that add to the target.
Initialize the empty sequenceFor values [1,2,3], ways[0]=1 counts the empty sequence. All positive totals start at zero.
0:1
base1001020304
indicestotal 0..4
base
0
indices
total 0..4
index 0
1

Recognize it
Use it when order matters, values may be reused, and every sequence reaching a total has one unambiguous final value that reduces it to a smaller solved total.
Keep true
Before processing total t, ways[0..t-1] contain exact ordered-sequence counts; after trying every num <= t, ways[t] counts each sequence exactly once by its final number.
Reuse it
To count ordered constructions, partition answers by the last decision and iterate states before choices; changing loop order can change the combinatorial object being counted.
For values [1,2,3], ways[0]=1 counts the empty sequence. All positive totals start at zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why are [1,3] and [3,1] counted separately without double-counting either sequence?
Read it this way: With values (1,2) and target 4, group by last value. Three sequences end in 1; two end in 2. Do 1,1,2 and 2,1,1 belong to the same final-value group?

Code

def combination_sum_four(nums: list[int], target: int) -> int:
   ways = [1] + [0] * target
   for total in range(1, target + 1):
      for num in nums:
         if num <= total:
            ways[total] += ways[total - num]
   return ways[target]

Cost: time and space.

This counts additions and integer slots, not fixed-width machine operations. Exact sequence counts can require growing bit widths.

Change Order Equivalence or Bound Length

Start from combination_sum_four. Each adaptation changes the counted object or the reason its dependencies terminate.

  1. Ignore value order.

    New task: Count unordered reusable-value combinations for a nonnegative target.

    Picture and change: Process denominations outside ascending totals. After each denomination, counts use only values processed so far. Deduplicate numeric values and reject nonpositive ones.

    Code: Complete replacement:

    def unordered_combinations(nums, target):
       values = sorted(set(nums))
       if any(value <= 0 for value in values):
          raise ValueError("positive values required")
       ways = [1] + [0] * target
       for value in values:
          for total in range(value, target + 1):
             ways[total] += ways[total - value]
       return ways[target]

    Check: [1,2,3], target four gives four. The source gives seven. This changes the answer, not just runtime.

    Use when: Permuting values should not create a new answer. After preprocessing unique values, the DP uses additions and slots.

  2. Bound length before allowing arbitrary integers.

    New task: Count ordered numeric-value sequences of at most a nonnegative integer max_length, including the empty sequence.

    Picture and change: Keep a separate sum-count map for each exact length. The length bound replaces positive-sum decrease as the termination argument.

    Code: Complete replacement, deduplicating numeric values:

    def bounded_sequence_count(nums, target, max_length):
       values = sorted(set(nums))
       counts, answer = {0: 1}, int(target == 0)
       for _ in range(max_length):
          next_counts = {}
          for total, count in counts.items():
             for value in values:
                next_counts[total + value] = next_counts.get(total + value, 0) + count
          counts = next_counts
          answer += counts.get(target, 0)
       return answer

    Check: [0,1], target one, length at most two gives [1], [0,1], [1,0]: three sequences. For [-1,1], target zero, the same bound counts empty, [-1,1] and [1,-1].

    Use when: A finite resource bound permits nonpositive values. Without it, zero-sum insertions can give infinitely many sequences. If sums occur at length , processing length bound takes work beyond preprocessing. Maps use slots; exact-integer costs also grow with bit width.

Rebuild Disjointness

Why do duplicate input values break the source’s final-value partition?

Answer: The loop adds the same numeric final group repeatedly. Deduplicate unless candidate identities intentionally define different choices.