The problem. You have n ropes with lengths ropes[i]. Joining two ropes of lengths a and b makes one rope of length a + b and costs a + b. Join all the ropes into one, and return the minimum total cost.
ropes = [4, 3, 2, 6] -> 29
ropes = [1, 2, 3] -> 9 (1 + 2 = 3, then 3 + 3 = 6)
ropes = [2, 2, 3, 3] -> 20 (2 + 2 = 4, 3 + 3 = 6, 4 + 6 = 10)
ropes = [5] -> 0 (nothing to join)Picture the joins as a tree: each join is a node, with the two ropes it joined below it. A rope's length is paid again at every join above it — so a rope that sits three joins deep is paid three times. To keep the total low, the long ropes should be joined as late as possible (paid few times) and the short ones early. Joining the two shortest first does exactly that, at every step.
This is the same argument that builds Huffman codes — the compression scheme behind ZIP and JPEG — where rare symbols get long codes and common ones short codes.
function minCost(ropes) { const r = [...ropes]; let cost = 0; while (r.length > 1) { r.sort((a, b) => b - a); // re-sort every round, longest first const a = r.pop(), b = r.pop(); // the two shortest are at the end cost += a + b; r.push(a + b); // the joined rope goes back in } return cost;}Time O(n² log n), space O(n). Java and C++ use 64-bit integers: with many long ropes, the total cost can pass 2³¹.
Sort once, shortest first. Each round takes the two shortest from the front and inserts the joined rope where it belongs — binary search finds the spot, but inserting still shifts everything after it.
function minCost(ropes) { const r = [...ropes].sort((a, b) => a - b); // sort once, shortest first let cost = 0; while (r.length > 1) { const a = r.shift(), b = r.shift(); // the two shortest are at the front const joined = a + b; cost += joined; let lo = 0, hi = r.length; // binary search for where the new rope belongs while (lo < hi) { const mid = (lo + hi) >> 1; if (r[mid] < joined) lo = mid + 1; else hi = mid; } r.splice(lo, 0, joined); // insert: shifts up to n ropes } return cost;}Time O(n²), space O(n).
Every round needs the two smallest values and adds one new value — the textbook heap job. Pop twice, push once: O(log n) per round.
Each round pops the two shortest ropes and pushes their join back.
Time O(n log n), space O(n). n − 1 rounds of two pops and one push.
O(n² log n)n − 1 joins, each paying for a full sort.
O(n)The list of ropes.
O(n²)[5]: nothing to join; the cost is 0.[3, 4]: one join, cost 7.[2, 2, 2, 2]: 4 + 4 + 8 = 16.long in Java and long long in C++.Each join inserts the new rope, shifting up to n ropes.
O(n)The list of ropes.
O(n log n)n − 1 rounds of two pops and one push, each log n.
O(n)The heap of ropes.