Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Heap (priority queue)

Cheapest way to join ropes

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

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.

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.