Bird
Raised Fist0

The following code attempts to compute the minimum cost to connect sticks using a min-heap. Identify the bug that causes incorrect results or infinite loops.

medium🐞 Bug Identification Q14 of Q15
Greedy Algorithms - Minimum Cost to Connect Sticks
The following code attempts to compute the minimum cost to connect sticks using a min-heap. Identify the bug that causes incorrect results or infinite loops.
ALine 3: Incorrect base case check for single stick
BLine 9: Adding cost before popping sticks
CLine 6: Not heapifying the sticks before processing
DLine 11: Not pushing the merged stick back into the heap
Step-by-Step Solution
Solution:
  1. Step 1: Review the merge loop

    The loop pops two smallest sticks and sums their lengths as cost.
  2. Step 2: Check if merged stick is reinserted

    The merged stick must be pushed back into the heap to continue merging. Missing this causes infinite loop or incorrect cost.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Without pushing merged stick, heap shrinks incorrectly -> infinite loop or wrong result [OK]
Quick Trick: Merged sticks must be pushed back to heap [OK]
Common Mistakes:
MISTAKES
  • Forgetting to push merged stick back
  • Incorrect base case handling
  • Misordering heap operations
Trap Explanation:
PITFALL
  • The missing push is subtle because code looks almost correct and may pass trivial tests.
Interviewer Note:
CONTEXT
  • Tests attention to detail and understanding of heap-based merging logic.
Master "Minimum Cost to Connect Sticks" in Greedy Algorithms

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 Greedy Algorithms Quizzes