Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Heap (priority queue)

Cheapest way to join ropes

Medium · Target 15 minutes · Heap (priority queue)· Type asked at

You have ropes of the given lengths. Joining two ropes of lengths a and b produces one rope of length a + b and costs a + b. Join ropes until one remains. Return the minimum possible total cost.

Examples

InputOutputWhy
ropes = [2, 4, 3]14Join 2 and 3 (cost 5), then 5 and 4 (cost 9).
ropes = [1, 8, 3, 5]301+3 = 4, 4+5 = 9, 9+8 = 17; total 30.
ropes = [5]0Nothing to join.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 1 ≤ ropes[i] ≤ 10⁴

Hints

Hint 1

A rope that is joined early is paid for again in every later join it takes part in. Which ropes should be joined first?

Hint 2

Always join the two shortest ropes available, then put the result back among the others.

Hint 3

You need the two smallest values repeatedly from a changing collection: that is what a min-heap is for.

Where people lose marks

  • Sorting once and joining left to right. After the first join, the new rope may be longer than the next rope in the list, and the order is wrong.
  • Adding only the final rope length to the cost. Every join is paid for, including the intermediate ones.
  • Overflow: with 10⁴ ropes of length 10⁴ the total reaches the order of 10¹⁰. Use 64-bit integers.
  • Returning the last rope’s length instead of the accumulated cost.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.