Prim’s and Kruskal’s Algorithms: Concepts, Differences, and Examples

Overview
Both Prim's and Kruskal's algorithm solve the exact same problem, find the minimum spanning tree (MST) of a weighted graph, the cheapest possible set of edges that connects every node with no cycles. They're both greedy, and on a graph with distinct edge weights they will always agree on the answer, they just get there by completely different routes: Prim's grows one tree outward from a starting node, Kruskal's builds a forest by grabbing the cheapest edge available anywhere, at every step. This page traces both by hand on one graph, verifies the arithmetic against working code, and clears up two claims about them that get stated wrong more often than not.
Spanning Tree and Minimum Spanning Tree, Defined
A spanning tree of a connected graph with N nodes is a subgraph that touches every node using exactly N-1 edges and contains no cycles. A graph can have many different spanning trees. A minimum spanning tree is the one spanning tree (or one of possibly several tied ones) whose edge weights add up to the smallest total possible.
One fact worth knowing before tracing either algorithm: when every edge weight in the graph is distinct, the MST is unique. That's not a coincidence for the example below, it's the reason Prim's and Kruskal's land on the exact same tree and the exact same total despite working completely differently. If some edge weights tie, there can be more than one valid MST, and different algorithms (or even the same algorithm run twice with ties broken differently) may return different, equally correct, trees.
What is Prim’s Algorithm in MST?
Prim's algorithm is used to find the minimum spanning tree for a given weighted graph. Given a weighted graph of n nodes, prim's algorithm is used to find the tree having n nodes and edges such that the sum of weights of these edges is the minimum of all possible trees.
The data structure used to select the minimum crossing edge determines Prim's complexity: a linear scan with an adjacency matrix takes O(V²), a binary min-heap with an adjacency list takes O(E log V), and a Fibonacci heap with an adjacency list takes O(E + V log V). The binary-heap implementation uses priority queues and min-heaps. To read more about Prim's algorithm and its implementation, see a step-by-step walkthrough of Prim's algorithm.
Spanning Tree(ST):
A spanning tree of a weighted graph with nodes is a subgraph that includes all vertices of the graph with the minimum possible number of edges i.e. there is a unique path between any two nodes of the subgraph. There can be more than one spanning tree.
Minimum Spanning tree(MST):
The minimum spanning tree of a weighted graph having nodes is the spanning tree having the minimum sum of weights of all edges.
In the example below given a graph and its spanning trees

The spanning trees of the above-weighted graph are shown below

The first spanning tree has the least weight i.e. 10 and hence is the minimum spanning tree.
Prim's algorithm:
Prim's algorithm is used to find the minimum spanning tree.
It is a greedy algorithm that constructs the minimum spanning tree by selecting the most optimal edge at that point.
To read more about prim's algorithm and its implementation click here Prim's algorithm
Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreWhat is the Kruskal Algorithm in MST?
Kruskal's algorithm is another greedy algorithm besides prim's which is used to find the minimum spanning tree from a given graph.
The main idea of Kruskal's algorithm is as follows:
Given a weighted graph with vertices and edges, the idea is to sort all the edges in increasing order of their weights, then we select the first edges such that they do not form a cycle within them.
It is guaranteed that those selected edges will construct the minimum spanning tree because there is no other way to include even smaller weight edges as we already considered the smallest weight edges.
To read more about Krushkal's algorithm click here Krushkal's algorithm
Examples
Let's go through examples of Prim's and Krushkal's algorithm one by one.
Prim’s Algorithm
Suppose you are given a weight graph as shown below, the task is to find the minimum spanning tree using Prim's algorithm, and list out all steps for finding the minimum spanning tree of the given graph.

Below are the steps of Prim's algorithm:
-
Start with any node in the graph and mark it visited and include it in the MST.
-
Iterate over all adjacent vertices of the chosen vertex which are not included in the MST and update their values and parent.
-
Repeat the above two steps until all the nodes are included in the MST.
To implement the above steps of the algorithm we need three arrays:
setMST[N]: A boolean array that keeps track of the nodes included in the MST.
value[N]: An integer array that keeps track of the minimum edge weight for a particular node.
parent[N]: An integer array that stores the parent of each node, the parent of starting node is set to -1.
Let's start simulating the algorithm for the above graph:
Initially, the status of the above-mentioned arrays is as follows:

First of all, we pick an arbitrary vertex in the graph that says 1.

The arrays will be as follows

Now, we select the edge with the least weight out of all edges going out of node 1.

The arrays will be updated as follows:

Next, we have edges and out of which we select because it has the least weight.

The arrays will be updated as follows:

Next, we have edges , , and out of which is chosen as it has the least weight.

The corresponding arrays will be updated as follows:

Next, we have edges , , and and we shall select the edge .

The corresponding arrays will be updated as follows:

Now, we have covered all the vertices and this must be the minimum spanning tree for the above example with weight equal to the sum of elements of array value i.e. which is indeed the answer.
Kruskal Algorithm
Suppose you are given a weight graph as shown below, the task is to find the minimum spanning tree using Kruskal's algorithm, and list out all steps for finding the minimum spanning tree of the given graph.

Below are the steps of Kruskal's algorithm:
- Sort all the edges in increasing order of their weight.
- Select the first edges such that they do not form any cycle within them.
Let's see the simulation of prim's algorithm:
We start from the lowest-weight edge

Now, we choose the second-lowest weight edge.

Next, we choose the third-lowest weight edge such that it does not form a cycle.

Now, we choose the fourth-lowest weight edge such that it does not form a cycle.

Here, we have selected all the vertices, therefore, this is the minimum spanning tree and the sum of the edge weights is .
Key Differences between Prims and Kruskal Algorithm
Although both prim's and Kruskal's algorithms are greedy algorithms used to find the minimum spanning tree for a given weighted graph there are few differences between prim's and Kruskal's algorithm in terms of time, space, and working mechanisms.
-
In prim's algorithm, we choose the nodes greedily i.e. the node is chosen at a point such that the edge weight for this node is minimum while in the case of Krushkal's algorithm we choose the minimum weight edges greedily.
-
In Kruskal's algorithm we sort the edges by weight in increasing order and then select the edges without cycle having minimum weight but in the case of Prim's algorithm, we choose the vertices considering the edge weights, and even if the number of edges goes high it still stays efficient. In the case of dense graphs, Prim's algorithm is better.
-
Time complexity for the Prim's algorithm is while for Krushkal it is .
-
Prim's algorithm only works on a connected graph because we need to select the adjacent node for a selected node with minimum weight, while Krushkal can work for the disconnected component as well.
Prim's and Kruskal's Comparison
| Feature | Prim's Algorithm | Kruskal's Algorithm |
|---|---|---|
| Core approach | Grows one tree outward from a starting vertex. | Sorts all edges and adds them in ascending order if they do not form a cycle. |
| Data structure | Priority queue / min-heap, or a simple array with an adjacency matrix. | Edge list sorted by weight and disjoint-set union (union-find). |
| Graph representation | Usually an adjacency list with a heap, or an adjacency matrix with a linear scan. | Usually an edge list. |
| Starting point | Starts from a chosen vertex. | Does not need a starting vertex. |
| Edge selection | Cheapest edge crossing from the current tree to an unvisited vertex. | Cheapest remaining edge that joins two different components. |
| Cycle handling | Avoids cycles by adding only a vertex outside the current tree. | Uses union-find to reject an edge whose endpoints already share a root. |
| Time complexity | O(V²) with matrix + linear scan; O(E log V) with binary heap + adjacency list; O(E + V log V) with Fibonacci heap. | O(E log E) overall; sorting dominates, while DSU operations are near-constant amortised. |
| Space complexity | O(V²) for an adjacency matrix; O(V + E) for an adjacency list and heap. | O(V + E) for the edge list and DSU. |
| Dense vs sparse graphs | Often suitable for dense graphs with an adjacency matrix; the binary-heap version can also be competitive on sparse graphs. | Often suitable for sparse graphs and edge-list inputs; sorting many dense-graph edges can cost more. |
| Disconnected graphs | One run from a start vertex covers only that component; restart to build a forest. | Naturally returns a minimum spanning forest. |
| Implementation difficulty | Requires maintaining a frontier of edges from the growing tree; a heap-based version needs priority-queue updates. | Requires sorting edges and implementing union-find for cycle detection. |
| Typical use | Dense network design where a starting vertex and adjacency representation are available. | Sparse networks or inputs already represented as an edge list. |
Where This Shows Up in Interviews
MST questions rarely ask you to recite either algorithm. They ask which one you would pick and why, and the answer is always about the graph, not the algorithm.
- Know the complexity of each algorithm with its data structure.
- Be ready for "what if the graph is disconnected?"
Scaler's DSA interview preparation course works through this pattern.
How Scaler Transformed Careers in Different Fields
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
Prim's Vs Kruskal's Algorithm
Prim's and Kruskal's algorithm besides having similarities also has a lot of differences in terms of their use cases, complexity, and other factors like speed.
Following are the key differences between Prim's and Kruskal's algorithms in table format.

Prim's vs Kruskal's: Key Differences
A few of the standard claims about these two need a more careful phrasing than they usually get:
| Prim's Algorithm | Kruskal's Algorithm | |
|---|---|---|
| Core approach | Grow one tree outward from a start node | Sort all edges, then add greedily using union-find |
| Typical time complexity | O(V²) with a simple array; O(E log V) with a binary heap and adjacency list | O(E log E) for the sort, which dominates; near O(E) for the union-find operations |
| Space complexity | O(V²) for an adjacency matrix, or O(V + E) with an adjacency list and heap | O(V + E) for the edge list and the union-find structure |
| Better suited to | Dense graphs (E close to V²), since it never needs to sort | Sparse graphs (E close to V), since sorting a short edge list is cheap |
| Needs a starting vertex? | Yes | No, it processes edges directly |
| Behaviour on a disconnected graph | Only finds the MST of the component containing the start node; other components are simply never reached | Naturally produces a minimum spanning forest, one tree per component, since edges between components are never available to begin with |
Two corrections worth flagging explicitly, since both get stated wrong constantly:
● "Prim's is O(N²), Kruskal's is O(E log N)" is only true for the simplest implementation of each. Swap Prim's array for a binary heap and adjacency list and it drops to O(E log V), competitive with Kruskal's on sparse graphs. The O(N²) figure describes one specific implementation choice, not something inherent to the algorithm.
● "Prim's only works on connected graphs, Kruskal's works on disconnected ones" overstates the difference. Neither algorithm magically spans a disconnected graph. Kruskal's naturally produces a minimum spanning forest on disconnected input, because it never needed a starting point to begin with, edges between components simply never appear as candidates. Prim's, anchored at one starting node, only ever finds the MST of that node's own connected component; extending it to the rest of the graph means explicitly restarting it once the frontier runs dry. The practical difference is real, Kruskal's handles this more gracefully without extra bookkeeping, but it isn't that one algorithm "works" and the other doesn't.
Working Code (Compiled and Run)
Real-World Applications
One correction here too: MST algorithms don't solve the travelling salesman problem, despite that claim showing up often, including on earlier versions of this page. TSP asks for the cheapest cycle that visits every node exactly once, an MST is a tree, not a cycle, and solves a different question. Where MST genuinely connects to TSP is as a building block inside approximation algorithms, doubling every edge of an MST and shortcutting repeated visits gives a tour at most twice the optimal length, and Christofides' algorithm refines that further using a matching step on top of the MST. The MST is an ingredient there, not the answer itself.
Where these algorithms are actually used directly:
● Network design: laying cable, pipeline, or road infrastructure to connect a set of locations at minimum total cost.
● Circuit design: minimising total wire length connecting components on a board.
● Approximation algorithms: the TSP and Steiner tree approximations mentioned above, where an MST gives a cheap, provably-bounded starting point.
● Clustering: single-linkage clustering builds a dendrogram directly from an MST, cutting the most expensive remaining edges to split data into clusters.
● Image segmentation: some computer vision techniques treat pixels as graph nodes and use MST-based cuts to separate regions.
Turn Learning into Career Growth
Common Mistakes
● Confusing the frontier in Prim's with only the new node's edges. The frontier is every unused edge crossing from the visited set to the unvisited set, not just edges from the most recently added node, most of them just happen to come from recent additions because older ones already got used.
● Forgetting the cycle check in Kruskal's and just taking the N-1 cheapest edges outright. That can include a cycle and miss the actual MST if two cheap edges happen to connect the same two components.
● Assuming there's exactly one MST in general. It's only guaranteed when all edge weights are distinct. With tied weights, multiple different trees can share the same minimum total.
● Quoting one Big-O figure per algorithm as if it were fixed. Both algorithms' complexity depends heavily on which data structure backs them, array vs heap for Prim's, naive scan vs union-find for Kruskal's.
FAQs
What is the main difference between Prim's and Kruskal's algorithm?
Prim's grows one tree from a selected starting vertex by choosing the cheapest edge that reaches an unvisited vertex. Kruskal's sorts all edges and adds the cheapest edge that connects two different components. Prim's is vertex-growth oriented; Kruskal's is edge-selection oriented.
Do Prim's and Kruskal's always give the same minimum spanning tree?
They always return a minimum spanning tree with the same minimum total weight when the graph is connected. If every edge weight is distinct, the MST is unique and both return the same edge set. With tied weights, multiple MSTs may exist, so their selected edges can differ.
What is the time complexity of Prim's algorithm?
With an adjacency matrix and linear scan, Prim's takes O(V²). With an adjacency list and binary min-heap, it takes O(E log V). With a Fibonacci heap and adjacency list, it takes O(E + V log V). State the graph representation and priority-queue implementation when quoting the bound.
What is the time complexity of Kruskal's algorithm?
Kruskal's takes O(E log E) time because sorting the E edges dominates the algorithm. After sorting, each edge is checked using disjoint-set union with path compression and union by rank, whose amortised cost is O(α(V)) per operation, effectively near-constant for practical inputs.
Which algorithm works on a disconnected graph?
Kruskal's naturally produces a minimum spanning forest, with one minimum spanning tree for each connected component. Prim's started from a single vertex only covers that vertex's component. To obtain a forest with Prim's, restart it from every vertex that remains unvisited.
Conclusion
Prim's and Kruskal's are the same idea, be greedy, never form a cycle, wearing two different implementations. Prim's grows a single tree by always taking the cheapest edge on its current frontier, and works best when a graph is dense and a heap is available. Kruskal's sorts every edge once and adds greedily with a union-find structure to reject cycles, and wins when the edge list is short relative to the number of nodes. On a graph with distinct weights, as most exam questions are, they will always agree, so knowing both isn't redundant, it's insurance against whichever one the problem's structure happens to favour.