Bird
Raised Fist0

Examine the following buggy backtracking code for generating combinations of size k from 1 to n. Which line contains the subtle bug that causes incorrect or duplicate results?

medium🐞 Bug Identification Q14 of Q15
Subsets & Combinations - Combinations (Choose K from N)
Examine the following buggy backtracking code for generating combinations of size k from 1 to n. Which line contains the subtle bug that causes incorrect or duplicate results?
ALine where for loop iterates from start to n + 1
BLine where recursion starts from 1 instead of 0
CLine where path.pop() is called after recursion
DLine where path is appended directly to result without copying
Step-by-Step Solution
  1. Step 1: Identify how results are stored

    Appending path directly stores a reference, so all entries in result point to the same list object.
  2. Step 2: Understand consequence

    All combinations in result become identical after backtracking modifies path, causing duplicates or incorrect results.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Appending a copy (path[:]) fixes the bug [OK]
Quick Trick: Always append a copy of path, not the path itself [OK]
Common Mistakes:
MISTAKES
  • Forgetting to copy path before appending to result
Trap Explanation:
PITFALL
  • Appending path directly looks correct but causes subtle reference sharing bugs.
Interviewer Note:
CONTEXT
  • Tests attention to detail and understanding of mutable references in recursion.
Master "Combinations (Choose K from 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