DSA
    advanced

    Minimum Spanning Tree (Kruskal's Algorithm)

    Minimum Spanning Tree (Kruskal's Algorithm)

    Visualize Kruskal's MST algorithm: sort all edges by weight, then greedily add the cheapest edges that don't create a cycle using Union-Find. Demonstrates why a greedy approach guarantees a minimum spanning tree on connected graphs.

    ⏱ O(E log E)
    💾 O(V + E)
    Ready
    0
    MST Weight
    0/4
    Edges Added
    431257601234
    Sorted Edges (Kruskal processes in this order)
    1-2:1
    1-3:2
    0-2:3
    0-1:4
    2-4:5
    3-2:6
    3-4:7

    Kruskal's MST: Sort all 7 edges by weight: (1-2,w=1), (1-3,w=2), (0-2,w=3), (0-1,w=4), (2-4,w=5), (3-2,w=6), (3-4,w=7). Use Union-Find to detect cycles.

    50%
    Live Variables
    nodes5
    edges7

    Kruskal’s algorithm

    Sequence

    Order the steps of building a minimum spanning tree.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    When is Kruskal preferred over Prim?

    The short version

    Imagine connecting all houses in a neighborhood with water pipes. You want to use the minimum total pipe length while ensuring every house gets water. MST finds the cheapest way to connect everyone.

    In more depth

    Two Approaches

    Kruskal's Algorithm:

    1.Sort all edges by weight
    2.For each edge, if it connects two different components (Union-Find), add it
    3.Stop when we have V-1 edges

    Prim's Algorithm:

    1.Start from any node, add to MST
    2.Add all edges from MST nodes to priority queue
    3.Pop minimum edge that leads to a new node, add that node
    4.Repeat until all nodes in MST

    When to Use:

    Kruskal: Sparse graphs, edges already available
    Prim: Dense graphs, when using adjacency matrix

    Key Gotchas:

    MST may not be unique (multiple MSTs possible)
    Graph must be connected (check at end!)
    For disconnected graphs, build MST per component

    When to reach for this

    • Connect all nodes with minimum total edge weight
    • Network/cable/pipe laying problems
    • Keywords: 'minimum cost to connect', 'spanning tree'
    • Any graph edge selection with global minimum goal

    Interview Questions

    Amazon
    Google
    Uber
    Bloomberg
    Google
    Microsoft
    Netflix
    LinkedIn
    Meta
    Palantir
    LinkedIn
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required