DSAPROB12 - Editorial

Problem link - The Wire Connection

Problem statement :

Given N wires of different lengths, you are to connect these wires into one single wire with the minimum total cost. The cost to connect any two wires equals the sum of their lengths. You need to return the minimum total cost of connecting all the wires.

Approach

The key idea to solve this problem is to use a min-heap (priority queue) because it allows us to efficiently retrieve the two smallest elements repeatedly, which is crucial for minimizing the cost. By always connecting the two smallest wires first, we ensure that we keep the incremental costs as low as possible.

Here’s how we use this approach:

  • Step 1: Insert all wire lengths into the min-heap.

  • Step 2: While there is more than one wire in the heap, do the following:

    • Remove the two smallest wires (these are the two least costly to combine).
    • Add their combined length to the total cost.
    • Insert the combined wire back into the heap to be used in future combinations.
  • Step 3: Continue until only one wire remains in the heap, which is the fully connected wire, and the total cost accumulated will be the minimum cost.

This greedy approach ensures that we always connect the smallest available wires first, which minimizes the overall cost of combining all the wires.

Time Complexity:

  • Heap Initialization: O(n log n), where n is the number of wires. Building the heap from the list of wire lengths takes O(n log n) time.

  • Heap Operations: O(n log n), where n is the number of wires. Each heap operation (extraction and insertion) takes O(log n) time, and you perform these operations approximately n times.

Space Complexity:

  • Min-Heap Storage: O(n), where n is the number of wires. The heap stores all wire lengths.

  • Additional Variables: O(1) for variables like totalCost, first, second, and cost