VOOZH about

URL: https://www.geeksforgeeks.org/dsa/connect-n-ropes-minimum-cost/

⇱ Connect n ropes with minimum cost - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Connect n ropes with minimum cost

Last Updated : 18 Oct, 2025

Given an array arr[] of rope lengths, connect all ropes into a single rope with the minimum total cost. The cost to connect two ropes is the sum of their lengths.

Examples:

Input: arr[] = [4, 3, 2, 6]
Output: 29
Explanation: Minimum cost to connect all ropes into a single rope is
Connect ropes 2 and 3 - [4, 5, 6], cost = 5
Connect ropes 4 and 5 - [9, 6], cost = 9
Connect ropes 9 and 6 - [15], cost = 15
Total cost = 5 + 9 + 15 = 29

👁 Connect-n-ropes-with-minimum-cost

Input: arr[] = [10]
Output: 0

[Naive Approach] Greedy with Repeated Sorting - O(n2*log(n)) Time and O(n) Space

The idea is to always connect the two shortest ropes first, minimizing the cost at each step using a greedy approach. We repeatedly sort the array, pick the two smallest ropes, connect them, and add their combined length back into the array while accumulating the cost. This process continues until only one rope remains.


Output
29

[Expected Approach] Greedy with Heap - O(n*log(n)) Time and O(n) Space

Always connect the two smallest ropes first to minimize total cost, similar to Huffman coding.The idea is to use a min-heap(priority queue) and push all elements into it. While the heap contains more than one element, repeatedly extract the two smallest values, add them, and insert the sum back into the heap. Continue until one rope remains, then return the total cost.


Output
29
Comment