Scrivio Interview library
Heaps and top kStacks, queues and heapsReported 21 times · 13 min read · updated 14 November 2026

Join n ropes into one, where each join costs the sum of the two lengths. Find the lowest total cost.

1What the joining costs, seen as stacks of paper

Think of an office with a counting machine for paper. To join two stacks into one, you feed both through the machine, and it charges one coin for every sheet it counts. Suppose you have four small stacks to make into one big pile. A sheet in a stack that is joined early goes through the machine again at every later join. So the order matters, even though the final pile is the same size either way.

Our problem is the same, with ropes in place of stacks. We have n ropes with given lengths. Joining two ropes makes one rope whose length is their sum, and the join costs exactly that sum. We keep joining until one rope is left, and we want the smallest total cost.

Let us work the example by hand, with ropes of lengths 4, 3, 2 and 6. Joining from left to right, we pay 4 + 3 = 7, then 7 + 2 = 9, then 9 + 6 = 15, which is 31 in all. Now try joining the two shortest first: 2 + 3 = 5, then the shortest two are 4 and 5, which make 9, and finally 6 + 9 = 15. That is 5 + 9 + 15 = 29. The final rope is 15 long both times, but the second order paid 2 less.

PictureThe four ropes we are given

Each bar is one rope, in the order given.

  1. 4326
    ropes
    4
    joins needed
    3
    best cost
    29

    1The ropes are 4, 3, 2 and 6 long. The shortest two, 2 and 3, are the ones we will join first.

What to assume

May we join any two ropes, or only neighbours?
Any two.
How many ropes, and how long?
We assume up to about 100,000 ropes with positive int lengths, so the total can pass the int range and we use long.
What do one rope or no ropes cost?
Zero, since no join is needed.
Do we return the order too?
Only the cost.

The problem is smaller than it looks. However many ropes there are, each join is a simple addition, and there are always exactly n - 1 joins, because each one turns two ropes into one. The only question is which two to pick at each step, and we will find a simple rule for that.

A careful candidate asks a few questions first. May we join any two ropes, or only neighbours? Any two. How many ropes, and how long? We assume up to about 100,000 ropes with positive int lengths, so the total can pass the int range and we use long. What do one rope or no ropes cost? Zero, since no join is needed. Do we return the order too? Only the cost.

2How to recognise the greedy heap pattern

A beginner reading this question for the first time often thinks the order cannot matter, because the final rope is always the sum of all the lengths. That is half right, and it is the most common mistake: the final rope's length is fixed, but the cost adds up every rope made along the way. Once you see that, the question becomes which order keeps the in-between ropes small.

The first clue is the phrase lowest total cost over a repeated step. When a problem asks for the best result from repeating a simple step, it is worth asking whether one obvious choice at each step is always safe. Choosing the best-looking option at each step, without looking ahead, is called a greedy method.

The second clue is that each join puts a new rope back into the pool. So the set we choose from keeps changing, and the new rope may be longer than ropes not yet used. We need a container that can hand us the two shortest ropes again and again, even as new ropes are added.

Those clues point to the heaps and top k family. A heap is a structure that keeps its smallest item on top, a min-heap, and lets us take the top or add a new item in about log n steps. The general rule is that when a problem repeatedly takes the smallest or largest items from a changing collection and puts results back, a heap does the bookkeeping, and the remaining work is to show that the greedy choice is safe.

Some methods look similar but do not fit. Sorting once and walking through the lengths fails, because the joined ropes must go back among the others in the right place. Dynamic programming, which tries every split and remembers results, is needed only when we may join neighbours alone; here any two ropes may join, so the greedy rule is both simpler and correct.

3The brute force, trying every order of joins

The honest first attempt, the brute force, is the one that is certainly correct: try every possible order and keep the cheapest. For the first join we try every pair, for each of those we try every pair of what remains, and so on, until one rope is left. It is a good start, because it gives us a way to check any cleverer answer.

On our example there are 6 pairs to choose from four ropes, then 3 pairs from the three ropes left, then 1. So there are 6 x 3 x 1 = 18 complete orders. We ran the code and recorded every total. They range from 29 up to 38, and only one of the 18 orders reaches 29, the one that joins 2 and 3 first and then 4 and 5.

Java
static long tryAllOrders(List<Long> ropes) {
if (ropes.size() <= 1) return 0; // one rope left: nothing more to pay
long best = Long.MAX_VALUE;
for (int i = 0; i < ropes.size(); i++) {
for (int j = i + 1; j < ropes.size(); j++) { // every pair could be the next join
List<Long> next = new ArrayList<>(ropes);
long joined = next.get(i) + next.get(j);
next.remove(j); // remove j first so i keeps its place
next.remove(i);
next.add(joined);
best = Math.min(best, joined + tryAllOrders(next));
}
}
return best;
}

Now let us count in general. With n ropes there are n(n - 1) / 2 choices for the first join, then (n - 1)(n - 2) / 2, and so on. Multiplying those together grows faster than n factorial, the product of all the whole numbers from 1 up to n. It is fine for four ropes and hopeless for twenty.

So where is the waste? The brute force explores orders that are obviously bad, such as joining the two longest ropes first, and it works out the same leftover sets of ropes again and again in different branches. If we knew which join is always a safe first move, we could make it and never look at the other branches at all.

4Getting to the rule of joining the two shortest

Let us go back to the paper stacks and ask how many times each sheet is paid for. A sheet is counted every time its stack takes part in a join. In the same way, a rope's length is paid once for every join it is part of, either itself or inside a bigger rope. In the left-to-right order, the 4 was paid in all three joins, at 7, at 9 and at 15.

We can draw the joins as a tree. The original ropes are the leaves at the bottom, and each join is a parent above the two ropes it joined. A rope that sits d joins deep is paid d times, so the total cost is each length times its depth, added up. The picture shows both orders from our example drawn this way.

Step throughEvery join drawn as a tree

Leaves are the original ropes; each parent is a join. A rope is paid once for every level above it.

  1. 15967243
    order
    left to right
    cost
    7 + 9 + 15 = 31

    1Joining left to right: 4 + 3 = 7, 7 + 2 = 9, 9 + 6 = 15. The 4 and the 3 sit three joins deep, so the cost is 4x3 + 3x3 + 2x2 + 6x1 = 31.

  2. 15694523
    order
    two shortest first
    cost
    5 + 9 + 15 = 29

    2Joining the shortest first puts 2 and 3 deepest and 6 near the top: 2x3 + 3x3 + 4x2 + 6x1 = 29.

Now comes the question a beginner should ask, which ropes we want deep in the tree. The deep ones are paid many times, so they should be the short ones, and the long ropes should sit near the top, paid only once or twice. Joining the two shortest ropes first is exactly what puts them at the bottom.

Why is it always safe, and not just good on this example? Think of any cheapest tree. Its deepest level has two leaves joined together. If those two were not the two shortest ropes, we could swap a shortest rope into that deep place and a longer rope out of it. The shorter length would get the bigger multiplier, so the cost could only stay the same or go down. So some cheapest tree joins the two shortest ropes first. After that join we have the same problem with one rope fewer, and the same argument applies again. This is the same reasoning that makes Huffman coding, a well known way to compress text, optimal.

The last step is speed. A middle step scans the whole list for the two shortest ropes before every join, which is O(n) per join and O(n squared) in all. A min-heap does better: it hands us each shortest rope in O(log n) and takes the joined rope back in O(log n).

5Watching the heap join the ropes

The picture plays the method on our ropes. Each bar is a rope in the heap, drawn shortest first so you can see which two are on top. The two ropes being joined are marked as looked at, and a rope that was just made is marked as done. The panel keeps the running total.

Watch the joined ropes come back. Each one is longer than either of its parts, yet it may still be one of the shortest in the pool, as the rope of 5 is in the third frame.

Step throughJoining 4, 3, 2 and 6, always the two shortest

Each bar is a rope in the heap, drawn shortest first. The two ropes being joined are marked as looked at; a new rope is marked as done.

  1. 2346
    pool
    2, 3, 4, 6
    total
    0

    1The four ropes go into a min-heap. Drawn shortest first, the pool is 2, 3, 4, 6, and nothing has been paid yet.

  2. 2346
    joining
    2 + 3 = 5
    total
    0 + 5 = 5

    2The heap hands us its two shortest ropes, 2 and 3. Joining them makes a rope of 5 and costs 5.

  3. 456
    pool
    4, 5, 6
    total
    5

    3The new rope of 5 goes back into the pool. It is longer than 4, so the heap puts it after 4. Three ropes are left.

  4. 456
    joining
    4 + 5 = 9
    total
    5 + 9 = 14

    4The two shortest are now 4 and the joined rope 5. Joining them makes 9 and costs 9.

  5. 69
    pool
    6, 9
    total
    14

    5The rope of 9 goes back. The pool is 6 and 9, and 9 already contains the 2, the 3 and the 4.

  6. 69
    joining
    6 + 9 = 15
    total
    14 + 15 = 29

    6Only two ropes remain, 6 and 9, so they are the two shortest. Joining them makes 15 and costs 15.

  7. 15
    pool
    15
    total
    29
    joins
    3, one fewer than ropes

    7One rope of 15 is left, so the loop stops. The total paid is 5 + 9 + 15 = 29, the lowest of all 18 possible orders.

In the second frame the heap gives us 2 and 3, and we pay 5. In the fourth, the shortest two are 4 and our new rope of 5, not 4 and 6, which is why the heap must take joined ropes back instead of keeping them aside. We pay 9 and the total reaches 14.

The last join makes 15 and brings the total to 29. Count the joins: three, one fewer than the four ropes. And 29 matches the cheapest of the 18 orders that the brute force tried.

6The complete Java program

Here is the whole program, with the minCost method and a main that tries our example, a second example, a single rope, no ropes at all, and three very long ropes whose total passes the int range. Each comment shows what that line prints.

Java
import java.util.*;
public class ConnectRopes {
// Always join the two shortest ropes; a min-heap hands them to us in O(log n).
static long minCost(int[] lengths) {
PriorityQueue<Long> heap = new PriorityQueue<>();
for (int len : lengths) heap.offer((long) len);
long total = 0;
while (heap.size() > 1) {
long joined = heap.poll() + heap.poll(); // the two shortest ropes
total += joined; // pay for this join
heap.offer(joined); // the new rope goes back in
}
return total; // 0 when there are 0 or 1 ropes
}
public static void main(String[] args) {
System.out.println(minCost(new int[] {4, 3, 2, 6})); // 29
System.out.println(minCost(new int[] {1, 2, 3, 4, 5})); // 33
System.out.println(minCost(new int[] {7})); // 0
System.out.println(minCost(new int[] {})); // 0
System.out.println(minCost(new int[] {1_000_000_000, 1_000_000_000, 1_000_000_000})); // 5000000000
}
}

Let us read minCost in the order it runs. First it makes a PriorityQueue of Long, which in Java is a min-heap unless we ask otherwise, and offers every length into it, widened to long. total starts at 0, because nothing has been paid yet.

The while loop runs as long as more than one rope is left. Inside, heap.poll() + heap.poll() takes the shortest rope and then the next shortest and adds them. We add that sum to total, because this join costs exactly its length, and we offer the joined rope back into the heap so it can take part in later joins.

When one rope is left, the loop stops and we return total. With zero ropes or one, the loop never runs and we return 0. So main prints 29, then 33 for ropes 1 to 5, then 0 and 0, and finally 5000000000 for the three long ropes.

Why Long inside the heap and not only for the total? Two ropes of a billion each make a rope of two billion, which is already larger than Integer.MAX_VALUE. If the heap held ints, that joined rope would overflow before we even added it to the total.

7How much it costs, and the cases at the edges

Let us count on the example first. Four offers fill the heap, and each of the three joins does two polls and one offer, so 13 heap operations in all, each touching only a level or two of a tiny tree. In general, n offers and n - 1 joins of three operations each make about 4n operations of O(log n), so the time is O(n log n).

The heap holds at most n ropes at any moment, and fewer after each join, so the extra space is O(n).

Comparing the ways to join the ropes
ApproachTimeExtra space
Brute force: try every orderworse than n!O(n^2) for the lists on the recursion stack
Greedy, scanning for the two shortestO(n^2)O(n)
Greedy with a min-heapO(n log n)O(n)

With zero ropes or one rope, the loop never runs and we return 0, which matches what we agreed. Equal lengths need nothing special, since either of two equal shortest ropes is a fine choice. Very large totals are safe because every sum is a long. And negative lengths are not allowed by the problem; if they were, the cost would no longer behave like a length, and the greedy argument would not hold.

8Follow-up questions

Can we sort once and avoid the heap?

Yes, with two queues. We sort the lengths into the first queue and keep a second queue for joined ropes. Each joined rope is at least as long as the one before it, so the second queue stays sorted on its own. At every step we take the two smallest fronts across both queues. After the O(n log n) sort the joins cost only O(n), which helps when the lengths already arrive sorted.

What if only neighbouring ropes may be joined?

Then the greedy rule is no longer safe, because the two shortest ropes may not be next to each other. The problem becomes interval dynamic programming: we work out the cheapest cost to join every range of ropes from i to j by trying every place to split it, and add the total length of the range. That is O(n cubed) time with prefix sums for the range totals.

What is the most common mistake here?

Returning the length of the final rope instead of the total cost. The final rope is always the sum of all lengths, whatever the order; the cost also counts every rope made along the way. The other is using int for the heap or the total, which overflows on long ropes.

9Conclusion

We joined the ropes at the lowest cost by always taking the two shortest from a min-heap, paying their sum, and putting the joined rope back. Each rope is paid once per join it is part of, so short ropes belong deep in the tree of joins and long ropes near the top, which is what the greedy rule produces. It takes O(n log n) time and O(n) space. The clue to remember is a repeated step that takes the smallest items from a changing pool: a heap does the bookkeeping, and the greedy choice is safe when the smallest items should be used most often.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the setup: any two ropes may be joined, each join costs the sum of the two lengths, I return only the total, and zero or one rope costs nothing.

Then, if they want more

Trying every order of joins is correct but grows faster than n factorial. The key observation is that each rope's length is paid once for every join it takes part in, so if I draw the joins as a tree, the cost is each length times its depth.

To keep that small, the shortest ropes should be deepest, so I always join the two shortest ropes available. An exchange argument shows it is safe: in any cheapest tree, swapping the two shortest ropes into the deepest pair can only lower the cost, and then the same problem remains with one rope fewer.

I store the lengths in a min-heap of longs, and while more than one rope is left I poll two, add their sum to the total, and offer the sum back. That is n - 1 joins of O(log n) each, so O(n log n) time and O(n) space, with long arithmetic to avoid overflow.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 21 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Join n ropes into one, where each join costs the sum of the two lengths. Find the lowest...": https://scrivio-interview-library.netlify.app/data-structures/solutions/join-n-ropes-into-one-where-each-join-costs-the-sum-of-the-two-l-996e3c/