We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium heap / priority queue problem, graded against 7 test cases (4 of them hidden).
A priority queue for "top k" and streaming-median questions.
Reach for it when you see: "Top/smallest k", a running median, or repeatedly needing the current minimum.
More Heap / Priority Queueproblems →Every connection's cost is the sum of the two pieces, so a stick connected early gets its length counted in every later merge that contains it. To minimize total cost, always merge the two shortest sticks first - the same greedy argument as Huffman coding, and an exchange argument proves it optimal.
A min-heap supports the loop efficiently: pop the two smallest, add their sum to the total, push the sum back, until one stick remains. The reference solution hand-rolls a small array-based binary min-heap, so it needs no imports or libraries in either language.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.