Combination Sum III solution explained

Combination Sum III asks for every set of k different digits from 1 to 9 that adds up to n. Because the pool is only nine digits, there are just 512 possible sets, so checking all of them with a bitmask is already fast; the interview answer is backtracking in increasing order with two bounds that cut dead branches early. If n is below the smallest possible sum of k digits or above the largest, the answer is empty before any search.

By Published 8 min read

The problem, in plain terms

Pick exactly k numbers from the digits 1 through 9. Each digit may be used at most once, and the picks must add up to n. Return all the different sets that work; the order of digits inside a set does not matter, so list each set once, usually in increasing order.

k = 3, n = 15  ->  8 sets
  1 5 9   1 6 8   2 4 9   2 5 8
  2 6 7   3 4 8   3 5 7   4 5 6

k = 4, n = 12  ->  1 2 3 6   1 2 4 5

k = 2, n = 17  ->  8 9          (the only pair that large)
k = 4, n = 1   ->  none         (four digits add up to at least 10)
Worked examples, made up for this page

Ask whether k can exceed 9 or be 0 and what to return then. A natural reading is that k = 0 with n = 0 has one answer, the empty set, and anything with k above 9 has none. Settle that with the interviewer rather than guessing.

What makes this variant different

Unlike Combination Sum II, there are no repeated values to worry about: the digits are distinct by construction, so no duplicate-skip rule is needed. The new ingredient is a fixed answer size. That adds a second stopping condition (you have used up your k slots) and makes tight numeric bounds possible, since the smallest and largest sums of a given number of digits are easy to compute. Interviewers often use it to see whether you notice that the input is tiny and say so.

Brute force: scan all 512 subsets

Number the digits 1 to 9 as bits 0 to 8 of an integer. Every integer from 0 to 511 is then one subset. For each, collect the digits whose bits are set, and keep the subset if it has k digits and the right sum. This does 512 × 9 small steps no matter what k and n are. For this specific problem that is perfectly fine, and many interviewers will accept it if you also explain how you would prune when the pool is larger.

// Bit d-1 of mask set means digit d is in the set; 512 sets in total.
function combinationSumDigits(k, n) {
  const out = [];
  for (let mask = 0; mask < 1 << 9; mask++) {
    const digits = [];
    let sum = 0;
    for (let d = 1; d <= 9; d++) {
      if (mask & (1 << (d - 1))) { digits.push(d); sum += d; }
    }
    if (digits.length === k && sum === n) out.push(digits);
  }
  return out;
}
JavaScript: one bitmask per subset of the nine digits.

The interview answer: backtracking with two bounds

Build each set in increasing order, so the next digit is always larger than the last one chosen. That alone prevents the same set from appearing in two orders. Then add two checks that use the fact that the remaining picks are distinct digits:

  • Too small to finish: with s slots left, even the s largest digits 9, 8, ... add up to a fixed amount. If that is less than what remains, no choice can work, so return.
  • Already too big: if you pick digit d now, the cheapest way to fill the s slots is d, d + 1, ..., d + s - 1. If that sum exceeds what remains, every larger d is worse too, so break out of the loop.

The loop also stops at 10 - s, because a first pick above that leaves no room for s - 1 bigger digits. With these cuts the recursion seldom enters a branch that has no way to succeed.

def combination_sum_digits(k, n):
    out, pick = [], []

    def go(low, slots, remaining):
        if slots == 0:
            if remaining == 0:
                out.append(pick[:])
            return
        if sum(range(10 - slots, 10)) < remaining:
            return                      # even the biggest digits fall short
        for d in range(low, 11 - slots):  # leave room for slots - 1 bigger digits
            if d * slots + slots * (slots - 1) // 2 > remaining:
                break                   # d, d + 1, ... already overshoots
            pick.append(d)
            go(d + 1, slots - 1, remaining - d)
            pick.pop()

    go(1, k, n)
    return out
Python: increasing digits with a lower and an upper bound on what is still reachable.

The first bound uses digits from 10 - slots up to 9. Note that it ignores low, so it is a safe but loose check: the true largest sum could be smaller if low is already near 9, and the loop range handles that case. Being exact is not required for correctness, only for speed, and here speed is not the issue.

Checking the bounds before searching

The smallest sum of k distinct digits is 1 + 2 + ... + k = k(k + 1) / 2, and the largest is 9 + 8 + ... + (10 - k) = k(19 - k) / 2. For k = 3 that is 6 to 24, and for k = 9 it is exactly 45, with one answer, all nine digits. If n is outside the range for the given k, return an empty list at once. Saying this out loud is a cheap way to show you think about the shape of the input before writing loops.

Complexity summary

The pool is fixed at nine digits, so every bound is a constant; C(9, k) is the number of k-digit sets
ApproachTimeExtra space
Bitmask scan512 × 9 steps, O(1) for this problemO(k) per answer
Backtracking with boundsAt most C(9, k) leaves, usually far fewerO(k) recursion and current pick
General version, digits 1 to mO(C(m, k) × k)O(k), plus the output
The pool is fixed at nine digits, so every bound is a constant; C(9, k) is the number of k-digit sets. Scroll sideways on a small screen.

When an interviewer says everything is constant, agree, then give the general form: with a pool of m numbers, the bitmask scan becomes O(2^m × m) while the pruned backtracking stays proportional to the number of k-sized sets it actually visits. That is why the backtracking answer is the one worth practicing.

Edge cases to test

  • n below k(k + 1) / 2, such as k = 4, n = 1: no answers.
  • n above k(19 - k) / 2, such as k = 2, n = 18: no answers, since 9 + 8 = 17.
  • k = 9, n = 45: one answer containing every digit.
  • k = 1: the answer is [n] when n is from 1 to 9, otherwise empty.
  • k larger than 9, or 0, handled the way you agreed with the interviewer.

Common mistakes

  • Starting the next digit at 1 instead of the last digit plus one, which produces 1 2 6 and 2 1 6 as separate answers.
  • Checking only the sum and not the count, so a two-digit set that reaches n is wrongly accepted when k is 3.
  • Using continue where break is valid, which is correct but ignores the sorted order you built.
  • Letting the loop run to 9 for the first slot even when s slots remain, then wondering why the recursion explores impossible branches.
  • Treating the answer count as large. There are at most C(9, 4) = 126 sets of any single size, so output size is never the problem.

How to explain it out loud

Fictional example

Naming the small input, then pruning anyway
Candidate
There are only nine digits, so 512 subsets. I could scan them all with a bitmask and it would be instant. I'll mention that and then write the version that scales.
Candidate
I'll pick digits in increasing order. With s slots left, if even the s largest digits can't reach the remainder, I stop. If d plus the next s minus 1 digits already passes it, I break, since bigger d only makes it worse.
Candidate
First I check n against k times k plus 1 over 2 and k times 19 minus k over 2. Outside that range the answer is empty without searching.

With a list that has repeated values and no size limit, the same backtracking needs a skip rule: see Combination Sum II. Asking whether a set of numbers splits into several groups with the same sum is Partition to K Equal Sum Subsets. Splitting a number into parts to make the largest product, rather than listing the parts, is Integer Break.

Natively for small-input practice

Problems with tiny inputs test judgment as much as code: do you say the brute force is fine, and do you still know how to prune? While you practice, Natively on Mac or Windows can read a problem from a screenshot and write its own approach and code, which you can hold up against the bounds you chose. The transcript of the session shows how you framed the trade-off. See AI support for coding interview prep.

Questions people ask

How do you solve Combination Sum III?

Backtrack over digits in increasing order, stopping when the slots are used. Prune when the largest remaining digits cannot reach the remainder, and break when the smallest possible continuation overshoots it.

Can you solve Combination Sum III with a bitmask?

Yes. The digits 1 to 9 have only 512 subsets, so checking each mask for k set bits and the right sum is fast and correct.

What is the time complexity of Combination Sum III?

With a fixed pool of nine digits it is constant: at most 512 subsets or C(9, k) leaves. For a pool of m numbers, pruned backtracking is about O(C(m, k) × k).

When does Combination Sum III have no answer?

When n is below k(k + 1) / 2 or above k(19 - k) / 2, the smallest and largest sums of k distinct digits, or when k is larger than 9.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP