Minimum Cost to Connect Sticks

MediumHeapheap

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You have sticks with positive integer lengths given by sticks. You may join any two sticks of lengths x and y into one stick of length x + y, paying a cost of x + y. Keep joining until exactly one stick remains. Return the minimum total cost. If there is only one stick to begin with, the cost is 0. Aim for O(n log n) time.

Examples

Input: sticks = [4,2,6]
Output: 18
Join 2 and 4 for 6, then join 6 and 6 for 12. Total 18.
Input: sticks = [9]
Output: 0
Nothing needs to be joined.

Constraints

  • 1 <= sticks.length <= 10^4
  • 1 <= sticks[i] <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More heap problems