Connect n ropes with minimum cost
Last Updated :
28 Mar, 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: We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3. Which makes the array [4, 5, 6]. Cost of this operation 2 + 3 = 5.
2) Now connect ropes of lengths 4 and 5. Which makes the array [9, 6]. Cost of this operation 4 + 5 = 9.
3) Finally connect the two ropes and all ropes have connected. Cost of this operation 9 + 6 =15. Total cost is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes.
Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three rope of 3, 2 and 10), then connect 10 and 3 (we get two rope of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38.
Input: arr[] = [10]
Output: 0
Explanation: Since there is only one rope, no connections are needed, so the cost is 0.
[Naive Approach] Greedy with Repeated Sorting - O(n^2*log(n)) Time and O(n) Space
The approach used in this solution is a greedy algorithm. The idea is to always connect the two smallest ropes first, as this minimizes the cost at each step. To achieve this, the array of rope lengths is sorted, and the two smallest ropes are chosen for connection. Their combined length is then added back into the array, and the process repeats until only one rope remains.
By sorting the ropes at each step, we ensure that the smallest ropes are always picked, minimizing the total connection cost. The algorithm continues until all ropes are merged into one, and the total cost is accumulated. This method ensures that the problem is solved with a minimal total cost.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to return the minimum cost of connecting the ropes.
int minCost(vector<int>& arr) {
int totalCost = 0;
while (arr.size() > 1) {
sort(arr.begin(), arr.end());
int first = arr[0];
int second = arr[1];
arr.erase(arr.begin());
arr.erase(arr.begin());
int cost = first + second;
totalCost += cost;
arr.push_back(cost);
}
return totalCost;
}
int main() {
vector<int> ropes = {4, 3, 2, 6};
cout << minCost(ropes) << endl;
return 0;
}
Java
// Function to return the minimum cost of connecting the ropes.
import java.util.*;
public class GfG {
public static int minCost(int[] arr) {
int totalCost = 0;
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int rope : arr) {
minHeap.add(rope);
}
while (minHeap.size() > 1) {
int first = minHeap.poll();
int second = minHeap.poll();
int cost = first + second;
totalCost += cost;
minHeap.add(cost);
}
return totalCost;
}
public static void main(String[] args) {
int[] ropes = {4, 3, 2, 6};
System.out.println(minCost(ropes));
}
}
Python
# Function to return the minimum cost of connecting the ropes.
def minCost(arr):
totalCost = 0
while len(arr) > 1:
arr.sort()
first = arr.pop(0)
second = arr.pop(0)
cost = first + second
totalCost += cost
arr.append(cost)
return totalCost
if __name__ == '__main__':
ropes = [4, 3, 2, 6]
print(minCost(ropes))
C#
// Function to return the minimum cost of connecting the ropes.
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
static int MinCost(List<int> arr) {
int totalCost = 0;
while (arr.Count > 1) {
arr.Sort();
int first = arr[0];
int second = arr[1];
arr.RemoveAt(0);
arr.RemoveAt(0);
int cost = first + second;
totalCost += cost;
arr.Add(cost);
}
return totalCost;
}
static void Main() {
List<int> ropes = new List<int> {4, 3, 2, 6};
Console.WriteLine(MinCost(ropes));
}
}
JavaScript
// Function to return the minimum cost of connecting the ropes.
function minCost(arr) {
let totalCost = 0;
while (arr.length > 1) {
arr.sort((a, b) => a - b);
const first = arr[0];
const second = arr[1];
arr.splice(0, 2);
const cost = first + second;
totalCost += cost;
arr.push(cost);
}
return totalCost;
}
const ropes = [4, 3, 2, 6];
console.log(minCost(ropes));
[Expected Approach] Greedy with Heap - O(n*log(n)) Time and O(n) Space
The idea is to connect the smallest two ropes first, as the lengths of the ropes that are picked early are included more than once in the total cost. This approach is similar to the concept used in Huffman Coding, where the smaller elements are combined earlier, which results in a smaller cost for subsequent operations.
To implement the idea, 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. Maintain a variable to track the total cost, incrementing it by the sum of the extracted values at each step. Once the process is complete, return the total cost.
C++
// C++ program for connecting n rope
// with minimum cost using min-heap
#include <bits/stdc++.h>
using namespace std;
int minCost(vector<int> &arr) {
// Create a priority queue
// By default 'less' is used which is for decreasing
// order and 'greater' is used for increasing order
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
// Java program for connecting n ropes
// with minimum cost using min-heap
import java.util.PriorityQueue;
class GfG {
public static int minCost(int[] arr) {
// Create a priority queue
// By default, the priority queue is in
// increasing order
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
# Python program for connecting n ropes
# with minimum cost using min-heap
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#
// C# program for connecting n ropes
// with minimum cost using min-heap
using System;
using System.Collections.Generic;
class GfG {
static int minCost(int[] arr) {
// Create a priority queue
SortedSet<(int Value, int Index)> pq =
new SortedSet<(int, int)>();
for (int i = 0; i < arr.Length; i++) {
pq.Add((arr[i], i));
}
// 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.Min.Value;
pq.Remove(pq.Min);
int second = pq.Min.Value;
pq.Remove(pq.Min);
// Connect the ropes: update result and
// insert the new rope to pq
res += first + second;
pq.Add((first + second, pq.Count + 1));
}
return res;
}
static void Main(string[] args) {
int[] arr = { 4, 3, 2, 6 };
Console.WriteLine(minCost(arr));
}
}
JavaScript
// JavaScript program for connecting n ropes
// with minimum cost using min-heap
function minCost(arr) {
// Create a min-heap and add all elements
const pq = new MinHeap();
arr.forEach(num => pq.push(num));
// Initialize result
let res = 0;
// While size of priority queue is more than 1
while (pq.size() > 1) {
// Extract shortest two ropes from pq
const first = pq.pop();
const second = pq.pop();
// Connect the ropes: update result and
// insert the new rope to pq
res += first + second;
pq.push(first + second);
}
return res;
}
class MinHeap {
constructor() {
this.heap = [];
}
// Insert a value into the heap
push(val) {
this.heap.push(val);
this.heapifyUp();
}
// Remove and return the smallest element
pop() {
if (this.heap.length === 1) {
return this.heap.pop();
}
const root = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown();
return root;
}
// Return the smallest element without removing it
top() {
return this.heap[0];
}
// Return the size of the heap
size() {
return this.heap.length;
}
// Restore the heap property upwards
heapifyUp() {
let index = this.heap.length - 1;
while (index > 0) {
const parentIndex = Math.floor(
(index - 1) / 2
);
if (
this.heap[index] >=
this.heap[parentIndex]
) {
break;
}
[
this.heap[index],
this.heap[parentIndex]
] = [
this.heap[parentIndex],
this.heap[index]
];
index = parentIndex;
}
}
// Restore the heap property downwards
heapifyDown() {
let index = 0;
const size = this.heap.length;
while (true) {
const leftChild = 2 * index + 1;
const rightChild = 2 * index + 2;
let smallest = index;
if (
leftChild < size &&
this.heap[leftChild] <
this.heap[smallest]
) {
smallest = leftChild;
}
if (
rightChild < size &&
this.heap[rightChild] <
this.heap[smallest]
) {
smallest = rightChild;
}
if (smallest === index) {
break;
}
[
this.heap[index],
this.heap[smallest]
] = [
this.heap[smallest],
this.heap[index]
];
index = smallest;
}
}
}
const arr = [4, 3, 2, 6];
console.log(minCost(arr));
Similar Reads
Heap Data Structure A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree.Basics
2 min read
Introduction to Heap - Data Structure and Algorithm Tutorials A Heap is a special tree-based data structure with the following properties:It is a complete binary tree (all levels are fully filled except possibly the last, which is filled from left to right).It satisfies either the max-heap property (every parent node is greater than or equal to its children) o
15+ min read
Binary Heap A Binary Heap is a complete binary tree that stores data efficiently, allowing quick access to the maximum or minimum element, depending on the type of heap. It can either be a Min Heap or a Max Heap. In a Min Heap, the key at the root must be the smallest among all the keys in the heap, and this pr
13 min read
Advantages and Disadvantages of Heap Advantages of Heap Data StructureTime Efficient: Heaps have an average time complexity of O(log n) for inserting and deleting elements, making them efficient for large datasets. We can convert any array to a heap in O(n) time. The most important thing is, we can get the min or max in O(1) timeSpace
2 min read
Time Complexity of building a heap Consider the following algorithm for building a Heap of an input array A. A quick look over the above implementation suggests that the running time is O(n * lg(n)) since each call to Heapify costs O(lg(n)) and Build-Heap makes O(n) such calls. This upper bound, though correct, is not asymptotically
2 min read
Applications of Heap Data Structure Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher prior
2 min read
Comparison between Heap and Tree What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Types of Heap Data Structure: Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The sa
3 min read
When building a Heap, is the structure of Heap unique? What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property sta
4 min read
Some other type of Heap
Easy problems on Heap
Check if a given Binary Tree is a HeapGiven a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).Every nodeâs v
15+ min read
How to check if a given array represents a Binary Heap?Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: ar
11 min read
Iterative HeapSortHeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
11 min read
Find k largest elements in an arrayGiven an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order.Examples:Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23]Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17]Table of Content[Nai
15+ min read
Kâth Smallest Element in Unsorted ArrayGiven an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read
Height of a complete binary tree (or Heap) with N nodesConsider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we tak
3 min read
Heap Sort for decreasing order using min heapGiven an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1}Output : arr[] = {10, 5, 3, 1}Input : arr[] = {1, 50, 100, 25}Output : arr[] = {100, 50, 25, 1}Prerequisite: Heap sort using min heap.Using Min Heap Implementation - O(n Log n) Time
11 min read