Minimum Cost of ropes

Pattern: Huffman-style merges

medium

Joining two ropes costs their total length, and a rope's length is paid again in every later join it is part of. Always join the two shortest ropes, using a min heap, so the short ones take part in the most joins.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Join all the ropes into one; joining two ropes costs the sum of their lengths. Return the least total cost. [4, 3, 2, 6] gives 29. The answer can exceed 32 bits. The catalogue has no practice link for this one.

Think first

  • How many times is each rope's length paid?
  • Which ropes should be paid for most often?
  • After a join, where does the new rope go?

Hints

    Brute force, and why it fails

    Try every order of joins: exponential.

    The key insight

    It is Huffman's problem: the total is each length times its depth in the joining tree, and joining the two smallest first is optimal.

    Dry run

    heap4 5 6
    cost5

    Ropes [4, 3, 2, 6]. Join 2 and 3: cost 5.

    Step 1 of 3

    The plan

    heap = ropes
    while size > 1: a = pop; b = pop; cost += a + b; push a + b
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    n - 1 joins on a heap.

    Edge cases

    • One rope: 0.
    • Two ropes: their sum.
    • Long lists: 64-bit totals.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long minCost(int[] ropes) {
            PriorityQueue<Long> heap = new PriorityQueue<>();
            for (int x : ropes) heap.add((long) x);
            long cost = 0;
            while (heap.size() > 1) {
                long a = heap.poll(), b = heap.poll();  // the two smallest
                cost += a + b;                          // joining them costs their sum
                heap.add(a + b);                        // and the result joins the pile
            }
            return cost;
        }
    }

    C++

    class Solution {
    public:
        long long minCost(vector<int>& ropes) {
            priority_queue<long long, vector<long long>, greater<long long>> heap(ropes.begin(), ropes.end());
            long long cost = 0;
            while (heap.size() > 1) {
                long long a = heap.top(); heap.pop();   // the two smallest
                long long b = heap.top(); heap.pop();
                cost += a + b;                          // joining them costs their sum
                heap.push(a + b);                       // and the result joins the pile
            }
            return cost;
        }
    };

    Python

    import heapq
    
    class Solution:
        def minCost(self, ropes: list[int]) -> int:
            heap = list(ropes)
            heapq.heapify(heap)
            cost = 0
            while len(heap) > 1:
                a, b = heapq.heappop(heap), heapq.heappop(heap)   # the two smallest
                cost += a + b                       # joining them costs their sum
                heapq.heappush(heap, a + b)         # and the result joins the pile
            return cost

    Common mistakes

    • Sorting once and adding left to right.
    • Forgetting to push the joined rope back.

    Similar problems