Find the MST weight

Graphs Minimum Spanning Tree Hard
  • Fun Fact: The concept of a Minimum Spanning Tree, as outlined in the problem statement, is a fundamental algorithm used within network design
  • It plays a key role in practical applications such as the design of computer, telecommunication, and transportation networks
  • In any such network, it is crucial to connect all nodes with the minimum possible cost, hence the need for an MST
  • It’s also used in data clustering algorithms (like hierarchical clustering) in machine learning, and image segmentation in computer vision

Given a weighted, undirected, and connected graph with V vertices numbered from 0 to V-1 and E edges.

The ith edge is represented by [ai,bi,wi], where ai and bi denotes the endpoint of the edge and the wi denotes the weight of the edge.

Find the sum of the weights of the edges in the Minimum Spanning Tree (MST) of the graph. 


A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.

Examples:


Input: V = 4, edges = [[0, 1, 1], [1, 2, 2], [2, 3, 3], [0, 3, 4]]

Output: 6

Explanation: 

Edges included in the MST:

[0, 1, 1] with weight 1

[1, 2, 2] with weight 2

[2, 3, 3] with weight 3

The total weight of the MST is 1 + 2 + 3 = 6. These edges form a spanning tree that connects all vertices (0, 1, 2, 3) with the minimum possible total edge weight, satisfying the MST properties.


Input: V = 3, edges = [[0, 1, 5], [1, 2, 10], [2,0,15]]

Output: 15

Explanation: 

Edges included in the MST:

[0, 1, 5] with weight 5

[1, 2, 10] with weight 10

The total weight of the MST is 5+10 = 15

Input: V = 4, edges = [[0, 1, 1], [1, 2, 2], [2, 3, 3], [0, 3, 4]]

Constraints

  • 2 ≤ V ≤ 103
  • V-1 ≤ E ≤ 104
  • 1 ≤ w ≤ 105

Hints

  • Sort edges in ascending order of weight. Use Disjoint Set (Union-Find with Path Compression & Union by Rank) to keep track of connected components. Iterate over sorted edges. If an edge does not form a cycle, include it in the MST and merge the components. If V-1 edges have been included, stop (MST is complete). Return the sum of MST edge weights.
  • Use a priority queue (min-heap) to always expand the lightest edge connected to the MST. Maintain a visited set and a cost array to track the cheapest edge connecting each vertex to the MST. Extract the minimum-weight edge and expand the MST iteratively until all vertices are included. Return the sum of MST edge weights.

Company Tags

Wayfair Texas Instruments Optum American Express Deloitte Bungie Walmart Rakuten Docker Instacart Freshworks Seagate Technology Unity Technologies Visa Qualcomm Airbnb Micron Technology Alibaba Splunk IBM Broadcom Square Activision Blizzard Philips Healthcare Roblox Google Microsoft Amazon Meta Apple Netflix Adobe