This is a premium problem. We're working on making it available for free soon.
Use these hints if you're stuck. Try solving on your own first.
How many times does every stick contribute to the answer?
Some of the sticks will be used more than the others. Which sticks should be used the most/least?
The sticks with long lengths cost a lot so we should use these the least.
What if we keep merging the two shortest sticks?
Solutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Connecting the smallest sticks first minimizes the cost added at each step. If larger sticks are combined early, their higher sum will be added multiple times in later operations, increasing the overall cost.
Yes, variations of this problem are commonly asked in technical interviews at large tech companies. It tests understanding of greedy algorithms, heap data structures, and the ability to optimize cumulative costs.
A min-heap or priority queue is the most suitable data structure. It allows efficient retrieval of the two smallest sticks in O(log n) time and keeps the sticks dynamically ordered as new combined sticks are added.
The optimal approach uses a greedy strategy with a min-heap (priority queue). At each step, you combine the two smallest sticks, add their sum to the total cost, and push the combined stick back into the heap. This guarantees the minimum possible total connection cost.