Bird
Raised Fist0

In the following backtracking code for Combination Sum III, which mistake causes incorrect results?

medium🐞 Bug Identification Q7 of Q15
Subsets & Combinations - Combination Sum III (K Numbers to N)
In the following backtracking code for Combination Sum III, which mistake causes incorrect results?
def backtrack(start, k, n, path, res):
    if k == 0 and n == 0:
        res.append(path)
        return
    for i in range(start, 10):
        if i > n:
            break
        backtrack(i + 1, k - 1, n - i, path + [i], res)
ANot pruning when i == n
BLoop should start from 1 instead of start
CMissing base case for k < 0
DAppending path directly without copying causes shared reference issues
Step-by-Step Solution
Solution:
  1. Step 1: Analyze append operation

    Appending path directly adds a new list each time due to path + [i], so no shared reference issue.
  2. Step 2: Check pruning condition

    The code breaks the loop if i > n, but does not prune when i == n, which can cause unnecessary recursion.
  3. Step 3: Correct pruning

    Adding pruning for i == n can optimize and prevent incorrect or extra results.
  4. Final Answer:

    Not pruning when i == n -> Option A
  5. Quick Check:

    Proper pruning avoids unnecessary recursion and incorrect results [OK]
Quick Trick: Prune when i >= n to avoid unnecessary recursion [OK]
Common Mistakes:
MISTAKES
  • Assuming path append causes shared references
  • Ignoring pruning conditions
  • Incorrect loop start
Trap Explanation:
PITFALL
  • Lack of pruning on i == n can cause extra recursion and incorrect results.
Interviewer Note:
CONTEXT
  • Tests understanding of pruning and recursion correctness.
Master "Combination Sum III (K Numbers to N)" in Subsets & Combinations

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Subsets & Combinations Quizzes