Min Cost to Connect Ropes

Last Updated : 7 Oct, 2026

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. Return the minimum possible cost.

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
Explanation: Since there is only one rope, no connections are needed, so the cost is 0.

Try It Yourself
redirect icon

[Naive Approach] Greedy with Repeated Sorting - O(n^2 * 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.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int minCost(vector<int>& arr) {
    int totalCost = 0;

    // Continue until only one rope remains
    while (arr.size() > 1) {
        
        // Sort ropes to get the two smallest lengths
        sort(arr.begin(), arr.end());

        // Pick the two smallest ropes
        int first = arr[0];
        int second = arr[1];

        // Remove the two ropes from the array
        arr.erase(arr.begin());
        arr.erase(arr.begin());

        // Cost of connecting these two ropes
        int cost = first + second;
        totalCost += cost;

        // Push the new rope back into the array
        arr.push_back(cost);
    }

    return totalCost;
}

int main() {
    vector<int> ropes = {4, 3, 2, 6};
    cout << minCost(ropes) << endl;

    return 0;
}
Java
import java.util.Arrays;

class GFG {

    static int minCost(int[] arr) {
        int totalCost = 0;
        int n = arr.length;

        // Continue until only one rope remains
        while (n > 1) {

            // Sort ropes to get the two smallest lengths
            Arrays.sort(arr, 0, n);

            // Pick the two smallest ropes
            int first = arr[0];
            int second = arr[1];

            // Cost of connecting these two ropes
            int cost = first + second;
            totalCost += cost;

            // Shift the array to remove the two smallest elements
            for (int i = 2; i < n; i++) {
                arr[i - 2] = arr[i];
            }

            // Place the new rope at the end
            arr[n - 2] = cost;

            // Reduce array size by 1 (two removed, one added)
            n--;
        }

        return totalCost;
    }

    public static void main(String[] args) {
        int[] ropes = {4, 3, 2, 6};
        System.out.println(minCost(ropes));
    }
}
Python
def minCost(arr):
    totalCost = 0

    # Continue until only one rope remains
    while len(arr) > 1:

        # Sort ropes to get the two smallest lengths
        arr.sort()

        # Pick the two smallest ropes
        first = arr[0]
        second = arr[1]

        # Remove the two ropes from the array
        arr.pop(0)
        arr.pop(0)

        # Cost of connecting these two ropes
        cost = first + second
        totalCost += cost

        # Push the new rope back into the array
        arr.append(cost)

    return totalCost

if __name__ == "__main__":
    ropes = [4, 3, 2, 6]
    print(minCost(ropes))
C#
using System;

class GFG {
    static int minCost(int[] arr) {
        int totalCost = 0;
        int n = arr.Length;

        // Continue until only one rope remains
        while (n > 1)
        {
            // Sort ropes to get the two smallest lengths
            Array.Sort(arr, 0, n);

            // Pick the two smallest ropes
            int first = arr[0];
            int second = arr[1];

            // Cost of connecting these two ropes
            int cost = first + second;
            totalCost += cost;

            // Shift the array to remove the two smallest elements
            for (int i = 2; i < n; i++)
            {
                arr[i - 2] = arr[i];
            }

            // Place the new rope at the end
            arr[n - 2] = cost;

            // Reduce array size by 1 (two removed, one added)
            n--;
        }

        return totalCost;
    }

    static void Main()
    {
        int[] ropes = { 4, 3, 2, 6 };
        Console.WriteLine(minCost(ropes));
    }
}
JavaScript
function minCost(arr) {
    let totalCost = 0;

    // Continue until only one rope remains
    while (arr.length > 1) {

        // Sort ropes to get the two smallest lengths
        arr.sort((a, b) => a - b);

        // Pick the two smallest ropes
        let first = arr[0];
        let second = arr[1];

        // Remove the two ropes from the array
        arr.splice(0, 2);

        // Cost of connecting these two ropes
        let cost = first + second;
        totalCost += cost;

        // Push the new rope back into the array
        arr.push(cost);
    }

    return totalCost;
}

// Driver code
let ropes = [4, 3, 2, 6];
console.log(minCost(ropes));

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.

C++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int minCost(vector<int> &arr) {

    // Create a min priority queue
    priority_queue<int, vector<int>,
               greater<int>> pq(arr.begin(), arr.end());

    // Initialize result
    int res = 0;

    // While size of priority queue is more than 1
    while (pq.size() > 1) {

        // Extract shortest two ropes from pq
        int first = pq.top();
        pq.pop();
        int second = pq.top();
        pq.pop();

        // Connect the ropes: update result and
        // insert the new rope to pq
        res += first + second;
        pq.push(first + second);
    }

    return res;
}

int main() {
    vector<int> arr = {4, 3, 2, 6};
    cout << minCost(arr);
    return 0;
}
Java
import java.util.PriorityQueue;

class GFG {
  
     static int minCost(int[] arr) {
      
        // Create a min priority queue
        PriorityQueue<Integer> pq = new PriorityQueue<>();
       
        for (int num : arr) {
            pq.add(num);
        }

        // Initialize result
        int res = 0;

        // While size of priority queue is more than 1
        while (pq.size() > 1) {
          
            // Extract shortest two ropes from pq
            int first = pq.poll();
            int second = pq.poll();

            // Connect the ropes: update result and
            // insert the new rope to pq
            res += first + second;
            pq.add(first + second);
        }

        return res;
    }

    public static void main(String[] args) {
      
        int[] arr = {4, 3, 2, 6};
        System.out.println(minCost(arr));
    }
}
Python
import heapq

def minCost(arr):
  
    # Create a priority queue
    # By default, heapq provides a min-heap
    heapq.heapify(arr)

    # Initialize result
    res = 0

    # While size of priority queue is more than 1
    while len(arr) > 1:
      
        # Extract shortest two ropes from pq
        first = heapq.heappop(arr)
        second = heapq.heappop(arr)

        # Connect the ropes: update result and
        # insert the new rope to pq
        res += first + second
        heapq.heappush(arr, first + second)

    return res

if __name__ == "__main__":
  
    arr = [4, 3, 2, 6]
    print(minCost(arr))
C#
using System;
using System.Collections.Generic;

class Program {
    static int minCost(int[] arr) {
        // Create a min-priority queue (element, priority)
        PriorityQueue<int, int> pq = new PriorityQueue<int, int>();

        // Insert all elements into the priority queue
        foreach (int x in arr) {
            pq.Enqueue(x, x);
        }

        // Initialize result
        int res = 0;

        // While size of priority queue is more than 1
        while (pq.Count > 1) {
            // Extract shortest two ropes from pq
            int first = pq.Dequeue();
            int second = pq.Dequeue();

            // Connect the ropes: update result and insert back
            int cost = first + second;
            res += cost;
            pq.Enqueue(cost, cost);
        }

        return res;
    }

    static void Main() {
        int[] arr = { 4, 3, 2, 6 };
        Console.WriteLine(minCost(arr));
    }
}
JavaScript
// Min-Heap helper functions
function heapPush(heap, val) {
    heap.push(val);
    let idx = heap.length - 1;
    while (idx > 0) {
        let parent = Math.floor((idx - 1) / 2);
        if (heap[idx] < heap[parent]) {
            [heap[idx], heap[parent]] = [heap[parent], heap[idx]];
            idx = parent;
        } else {
            break;
        }
    }
}

function heapPop(heap) {
    if (heap.length === 0) return null;
    if (heap.length === 1) return heap.pop();

    let top = heap[0];
    heap[0] = heap.pop();
    let idx = 0;
    let n = heap.length;

    while (true) {
        let smallest = idx;
        let left = 2 * idx + 1;
        let right = 2 * idx + 2;

        if (left < n && heap[left] < heap[smallest]) {
            smallest = left;
        }
        if (right < n && heap[right] < heap[smallest]) {
            smallest = right;
        }

        if (smallest !== idx) {
            [heap[idx], heap[smallest]] = [heap[smallest], heap[idx]];
            idx = smallest;
        } else {
            break;
        }
    }

    return top;
}

// Function to find the minimum cost of connecting ropes
function minCost(arr) {
    let heap = [];

    // Insert all elements into the min-heap
    for (let i = 0; i < arr.length; i++) {
        heapPush(heap, arr[i]);
    }

    let res = 0;

    // While size of heap is more than 1
    while (heap.length > 1) {
        // Extract shortest two ropes
        let first = heapPop(heap);
        let second = heapPop(heap);

        // Connect the ropes: update result and insert back
        let sum = first + second;
        res += sum;
        heapPush(heap, sum);
    }

    return res;
}

// Driver code (main function)

    let arr = [4, 3, 2, 6];
    console.log(minCost(arr));

Output
29
Comment