Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Kruskal’s Minimum Spanning Tree (MST) Algorithm
Next article icon

Prim’s Algorithm for Minimum Spanning Tree (MST)

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Prim’s algorithm is a Greedy algorithm like Kruskal’s algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way.

  • The algorithm starts with an empty spanning tree.
  • The idea is to maintain two sets of vertices. The first set contains the vertices already included in the MST, and the other set contains the vertices not yet included.
  • At every step, it considers all the edges that connect the two sets and picks the minimum weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing MST. 

A group of edges that connects two sets of vertices in a graph is called Articulation Points (or Cut Vertices) in graph theory. So, at every step of Prim’s algorithm, find a cut, pick the minimum weight edge from the cut, and include this vertex in MST Set (the set that contains already included vertices).

Working of the Prim’s Algorithm

Step 1: Determine an arbitrary vertex as the starting vertex of the MST. We pick 0 in the below diagram.
Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST. Since we consider only the edges that connect fringe vertices with the rest, we never get a cycle.
Step 6: Return the MST and exit


How to implement Prim’s Algorithm?

Follow the given steps to utilize the Prim’s Algorithm mentioned above for finding MST of a graph:

  • Create a set mstSet that keeps track of vertices already included in MST. 
  • Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign the key value as 0 for the first vertex so that it is picked first. 
  • While mstSet doesn’t include all vertices 
    • Pick a vertex u that is not there in mstSet and has a minimum key value. 
    • Include u in the mstSet. 
    • Update the key value of all adjacent vertices of u. To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if the weight of edge u-v is less than the previous key value of v, update the key value as the weight of u-v.

The idea of using key values is to pick the minimum weight edge from the cut. The key values are used only for vertices that are not yet included in MST, the key value for these vertices indicates the minimum weight edges connecting them to the set of vertices included in MST.

Below is the implementation of the approach:

C++
// A C++ program for Prim's Minimum // Spanning Tree (MST) algorithm. The program is // for adjacency matrix representation of the graph #include <bits/stdc++.h> using namespace std;  // A utility function to find the vertex with // minimum key value, from the set of vertices // not yet included in MST int minKey(vector<int> &key, vector<bool> &mstSet) {        // Initialize min value     int min = INT_MAX, min_index;      for (int v = 0; v < mstSet.size(); v++)         if (mstSet[v] == false && key[v] < min)             min = key[v], min_index = v;      return min_index; }  // A utility function to print the // constructed MST stored in parent[] void printMST(vector<int> &parent, vector<vector<int>> &graph) {     cout << "Edge \tWeight\n";     for (int i = 1; i < graph.size(); i++)         cout << parent[i] << " - " << i << " \t"              << graph[parent[i]][i] << " \n"; }  // Function to construct and print MST for // a graph represented using adjacency // matrix representation void primMST(vector<vector<int>> &graph) {          int V = graph.size();        // Array to store constructed MST     vector<int> parent(V);      // Key values used to pick minimum weight edge in cut     vector<int> key(V);      // To represent set of vertices included in MST     vector<bool> mstSet(V);      // Initialize all keys as INFINITE     for (int i = 0; i < V; i++)         key[i] = INT_MAX, mstSet[i] = false;      // Always include first 1st vertex in MST.     // Make key 0 so that this vertex is picked as first     // vertex.     key[0] = 0;        // First node is always root of MST     parent[0] = -1;      // The MST will have V vertices     for (int count = 0; count < V - 1; count++) {                  // Pick the minimum key vertex from the         // set of vertices not yet included in MST         int u = minKey(key, mstSet);          // Add the picked vertex to the MST Set         mstSet[u] = true;          // Update key value and parent index of         // the adjacent vertices of the picked vertex.         // Consider only those vertices which are not         // yet included in MST         for (int v = 0; v < V; v++)              // graph[u][v] is non zero only for adjacent             // vertices of m mstSet[v] is false for vertices             // not yet included in MST Update the key only             // if graph[u][v] is smaller than key[v]             if (graph[u][v] && mstSet[v] == false                 && graph[u][v] < key[v])                 parent[v] = u, key[v] = graph[u][v];     }      // Print the constructed MST     printMST(parent, graph); }  // Driver's code int main() {   	vector<vector<int>> graph = { { 0, 2, 0, 6, 0 },                         		{ 2, 0, 3, 8, 5 },                         		{ 0, 3, 0, 0, 7 },                         		{ 6, 8, 0, 0, 9 },                         		{ 0, 5, 7, 9, 0 } };      // Print the solution     primMST(graph);      return 0; } 
C
// A C program for Prim's Minimum // Spanning Tree (MST) algorithm. The program is // for adjacency matrix representation of the graph  #include <limits.h> #include <stdbool.h> #include <stdio.h>  // Number of vertices in the graph #define V 5  // A utility function to find the vertex with // minimum key value, from the set of vertices // not yet included in MST int minKey(int key[], bool mstSet[]) {     // Initialize min value     int min = INT_MAX, min_index;      for (int v = 0; v < V; v++)         if (mstSet[v] == false && key[v] < min)             min = key[v], min_index = v;      return min_index; }  // A utility function to print the // constructed MST stored in parent[] int printMST(int parent[], int graph[V][V]) {     printf("Edge \tWeight\n");     for (int i = 1; i < V; i++)         printf("%d - %d \t%d \n", parent[i], i,                graph[parent[i]][i]); }  // Function to construct and print MST for // a graph represented using adjacency // matrix representation void primMST(int graph[V][V]) {     // Array to store constructed MST     int parent[V];     // Key values used to pick minimum weight edge in cut     int key[V];     // To represent set of vertices included in MST     bool mstSet[V];      // Initialize all keys as INFINITE     for (int i = 0; i < V; i++)         key[i] = INT_MAX, mstSet[i] = false;      // Always include first 1st vertex in MST.     // Make key 0 so that this vertex is picked as first     // vertex.     key[0] = 0;        // First node is always root of MST     parent[0] = -1;      // The MST will have V vertices     for (int count = 0; count < V - 1; count++) {                  // Pick the minimum key vertex from the         // set of vertices not yet included in MST         int u = minKey(key, mstSet);          // Add the picked vertex to the MST Set         mstSet[u] = true;          // Update key value and parent index of         // the adjacent vertices of the picked vertex.         // Consider only those vertices which are not         // yet included in MST         for (int v = 0; v < V; v++)              // graph[u][v] is non zero only for adjacent             // vertices of m mstSet[v] is false for vertices             // not yet included in MST Update the key only             // if graph[u][v] is smaller than key[v]             if (graph[u][v] && mstSet[v] == false                 && graph[u][v] < key[v])                 parent[v] = u, key[v] = graph[u][v];     }      // print the constructed MST     printMST(parent, graph); }  // Driver's code int main() {     int graph[V][V] = { { 0, 2, 0, 6, 0 },                         { 2, 0, 3, 8, 5 },                         { 0, 3, 0, 0, 7 },                         { 6, 8, 0, 0, 9 },                         { 0, 5, 7, 9, 0 } };      // Print the solution     primMST(graph);      return 0; } 
Java
// A Java program for Prim's Minimum Spanning Tree (MST) // algorithm. The program is for adjacency matrix // representation of the graph  import java.io.*; import java.lang.*; import java.util.*;  class MST {      // A utility function to find the vertex with minimum     // key value, from the set of vertices not yet included     // in MST     int minKey(int key[], Boolean mstSet[])     {         // Initialize min value         int min = Integer.MAX_VALUE, min_index = -1;          for (int v = 0; v < mstSet.length; v++)             if (mstSet[v] == false && key[v] < min) {                 min = key[v];                 min_index = v;             }          return min_index;     }      // A utility function to print the constructed MST     // stored in parent[]     void printMST(int parent[], int graph[][])     {         System.out.println("Edge \tWeight");         for (int i = 1; i < graph.length; i++)             System.out.println(parent[i] + " - " + i + "\t"                                + graph[parent[i]][i]);     }      // Function to construct and print MST for a graph     // represented using adjacency matrix representation     void primMST(int graph[][])     {         int V = graph.length;                  // Array to store constructed MST         int parent[] = new int[V];          // Key values used to pick minimum weight edge in         // cut         int key[] = new int[V];          // To represent set of vertices included in MST         Boolean mstSet[] = new Boolean[V];          // Initialize all keys as INFINITE         for (int i = 0; i < V; i++) {             key[i] = Integer.MAX_VALUE;             mstSet[i] = false;         }          // Always include first 1st vertex in MST.         // Make key 0 so that this vertex is         // picked as first vertex         key[0] = 0;                // First node is always root of MST         parent[0] = -1;          // The MST will have V vertices         for (int count = 0; count < V - 1; count++) {                          // Pick the minimum key vertex from the set of             // vertices not yet included in MST             int u = minKey(key, mstSet);              // Add the picked vertex to the MST Set             mstSet[u] = true;              // Update key value and parent index of the             // adjacent vertices of the picked vertex.             // Consider only those vertices which are not             // yet included in MST             for (int v = 0; v < V; v++)                  // graph[u][v] is non zero only for adjacent                 // vertices of m mstSet[v] is false for                 // vertices not yet included in MST Update                 // the key only if graph[u][v] is smaller                 // than key[v]                 if (graph[u][v] != 0 && mstSet[v] == false                     && graph[u][v] < key[v]) {                     parent[v] = u;                     key[v] = graph[u][v];                 }         }          // Print the constructed MST         printMST(parent, graph);     }      public static void main(String[] args)     {         MST t = new MST();         int graph[][] = new int[][] { { 0, 2, 0, 6, 0 },                                       { 2, 0, 3, 8, 5 },                                       { 0, 3, 0, 0, 7 },                                       { 6, 8, 0, 0, 9 },                                       { 0, 5, 7, 9, 0 } };          // Print the solution         t.primMST(graph);     } } 
Python
# A Python3 program for  # Prim's Minimum Spanning Tree (MST) algorithm. # The program is for adjacency matrix  # representation of the graph  # Library for INT_MAX import sys   class Graph():     def __init__(self, vertices):         self.V = vertices         self.graph = [[0 for column in range(vertices)]                       for row in range(vertices)]      # A utility function to print      # the constructed MST stored in parent[]     def printMST(self, parent):         print("Edge \tWeight")         for i in range(1, self.V):             print(parent[i], "-", i, "\t", self.graph[parent[i]][i])      # A utility function to find the vertex with     # minimum distance value, from the set of vertices     # not yet included in shortest path tree     def minKey(self, key, mstSet):          # Initialize min value         min = sys.maxsize          for v in range(self.V):             if key[v] < min and mstSet[v] == False:                 min = key[v]                 min_index = v          return min_index      # Function to construct and print MST for a graph     # represented using adjacency matrix representation     def primMST(self):          # Key values used to pick minimum weight edge in cut         key = [sys.maxsize] * self.V         parent = [None] * self.V  # Array to store constructed MST         # Make key 0 so that this vertex is picked as first vertex         key[0] = 0         mstSet = [False] * self.V          parent[0] = -1  # First node is always the root of          for cout in range(self.V):              # Pick the minimum distance vertex from             # the set of vertices not yet processed.             # u is always equal to src in first iteration             u = self.minKey(key, mstSet)              # Put the minimum distance vertex in             # the shortest path tree             mstSet[u] = True              # Update dist value of the adjacent vertices             # of the picked vertex only if the current             # distance is greater than new distance and             # the vertex in not in the shortest path tree             for v in range(self.V):                  # graph[u][v] is non zero only for adjacent vertices of m                 # mstSet[v] is false for vertices not yet included in MST                 # Update the key only if graph[u][v] is smaller than key[v]                 if self.graph[u][v] > 0 and mstSet[v] == False \                 and key[v] > self.graph[u][v]:                     key[v] = self.graph[u][v]                     parent[v] = u          self.printMST(parent)   # Driver's code if __name__ == '__main__':     g = Graph(5)     g.graph = [[0, 2, 0, 6, 0],                [2, 0, 3, 8, 5],                [0, 3, 0, 0, 7],                [6, 8, 0, 0, 9],                [0, 5, 7, 9, 0]]      g.primMST() 
C#
// A C# program for Prim's Minimum Spanning Tree (MST) // algorithm. The program is for adjacency matrix // representation of the graph  using System; using System.Collections.Generic;  class MST {     // A utility function to find the vertex with minimum     // key value, from the set of vertices not yet included     // in MST     int MinKey(int[] key, bool[] mstSet)     {         // Initialize min value         int min = int.MaxValue, minIndex = -1;          for (int v = 0; v < mstSet.Length; v++)             if (!mstSet[v] && key[v] < min)             {                 min = key[v];                 minIndex = v;             }          return minIndex;     }      // A utility function to print the constructed MST     // stored in parent[]     void PrintMST(int[] parent, int[,] graph)     {         Console.WriteLine("Edge \tWeight");         for (int i = 1; i < graph.GetLength(0); i++)             Console.WriteLine(parent[i] + " - " + i + "\t" + graph[parent[i], i]);     }      // Function to construct and print MST for a graph     // represented using adjacency matrix representation     public void PrimMST(int[,] graph)     {         int V = graph.GetLength(0);          // Array to store constructed MST         int[] parent = new int[V];          // Key values used to pick minimum weight edge in         // cut         int[] key = new int[V];          // To represent set of vertices included in MST         bool[] mstSet = new bool[V];          // Initialize all keys as INFINITE         for (int i = 0; i < V; i++)         {             key[i] = int.MaxValue;             mstSet[i] = false;         }          // Always include first 1st vertex in MST.         // Make key 0 so that this vertex is         // picked as first vertex         key[0] = 0;          // First node is always root of MST         parent[0] = -1;          // The MST will have V vertices         for (int count = 0; count < V - 1; count++)         {             // Pick the minimum key vertex from the set of             // vertices not yet included in MST             int u = MinKey(key, mstSet);              // Add the picked vertex to the MST Set             mstSet[u] = true;              // Update key value and parent index of the             // adjacent vertices of the picked vertex.             // Consider only those vertices which are not             // yet included in MST             for (int v = 0; v < V; v++)                 // graph[u][v] is non zero only for adjacent                 // vertices of m mstSet[v] is false for                 // vertices not yet included in MST Update                 // the key only if graph[u][v] is smaller                 // than key[v]                 if (graph[u, v] != 0 && !mstSet[v] && graph[u, v] < key[v])                 {                     parent[v] = u;                     key[v] = graph[u, v];                 }         }          // Print the constructed MST         PrintMST(parent, graph);     }      public static void Main(string[] args)     {         MST t = new MST();         int[,] graph = new int[,] { { 0, 2, 0, 6, 0 },                                       { 2, 0, 3, 8, 5 },                                       { 0, 3, 0, 0, 7 },                                       { 6, 8, 0, 0, 9 },                                       { 0, 5, 7, 9, 0 } };          // Print the solution         t.PrimMST(graph);     } } 
JavaScript
// Number of vertices in the graph  let V = 5;  // A utility function to find the vertex with  // minimum key value, from the set of vertices  // not yet included in MST  function minKey(key, mstSet) {      // Initialize min value      let min = Number.MAX_VALUE, min_index = -1;       for (let v = 0; v < V; v++)          if (!mstSet[v] && key[v] < min) {             min = key[v];             min_index = v;          }      return min_index;  }   // A utility function to print the  // constructed MST stored in parent[]  function printMST(parent, graph) {      console.log("Edge   Weight");      for (let i = 1; i < V; i++)          console.log(parent[i] + " - " + i + "   " + graph[parent[i]][i]);  }   // Function to construct and print MST for  // a graph represented using adjacency matrix  function primMST(graph) {      // Array to store constructed MST      let parent = new Array(V);           // Key values used to pick minimum weight edge in cut      let key = new Array(V);           // To represent set of vertices included in MST      let mstSet = new Array(V);       // Initialize all keys as INFINITE      for (let i = 0; i < V; i++) {         key[i] = Number.MAX_VALUE;          mstSet[i] = false;      }      // Always include first vertex in MST.      key[0] = 0;      parent[0] = -1; // First node is always root of MST       // The MST will have V vertices      for (let count = 0; count < V - 1; count++) {          // Pick the minimum key vertex from the set of vertices not yet included in MST          let u = minKey(key, mstSet);           // Add the picked vertex to the MST Set          mstSet[u] = true;           // Update key value and parent index of the adjacent vertices of the picked vertex.          for (let v = 0; v < V; v++) {              // graph[u][v] is non-zero only for adjacent vertices of u              // mstSet[v] is false for vertices not yet included in MST              // Update the key only if graph[u][v] is smaller than key[v]              if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {                  parent[v] = u;                  key[v] = graph[u][v];              }          }      }       // Print the constructed MST      printMST(parent, graph);  }   // Driver code let graph = [      [ 0, 2, 0, 6, 0 ],      [ 2, 0, 3, 8, 5 ],      [ 0, 3, 0, 0, 7 ],      [ 6, 8, 0, 0, 9 ],      [ 0, 5, 7, 9, 0 ]  ];   // Print the solution  primMST(graph);  

Output
Edge 	Weight 0 - 1 	2  1 - 2 	3  0 - 3 	6  1 - 4 	5  

Time Complexity: O(V2), As, we are using adjacency matrix, if the input graph is represented using an adjacency list, then the time complexity of Prim’s algorithm can be reduced to O((E+V) * logV) with the help of a binary heap.
Auxiliary Space: O(V)

Optimized Implementation using Adjacency List Representation (of Graph) and Priority Queue

  1. We transform the adjacency matrix into adjacency list using ArrayList<ArrayList<Integer>>. in Java, list of list in Python
    and array of vectors in C++.
  2. Then we create a Pair class to store the vertex and its weight .
  3. We sort the list on the basis of lowest weight.
  4. We create priority queue and push the first vertex and its weight in the queue
  5. Then we just traverse through its edges and store the least weight in a variable called ans.
  6. At last after all the vertex we return the ans.
C++
#include<bits/stdc++.h> using namespace std;  // Function to find sum of weights of edges of the Minimum Spanning Tree. int spanningTree(int V, int E, vector<vector<int>> &edges) {        // Create an adjacency list representation of the graph     vector<vector<int>> adj[V];          // Fill the adjacency list with edges and their weights     for (int i = 0; i < E; i++) {         int u = edges[i][0];         int v = edges[i][1];         int wt = edges[i][2];         adj[u].push_back({v, wt});         adj[v].push_back({u, wt});     }          // Create a priority queue to store edges with their weights     priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;          // Create a visited array to keep track of visited vertices     vector<bool> visited(V, false);          // Variable to store the result (sum of edge weights)     int res = 0;          // Start with vertex 0     pq.push({0, 0});          // Perform Prim's algorithm to find the Minimum Spanning Tree     while(!pq.empty()){         auto p = pq.top();         pq.pop();                  int wt = p.first;  // Weight of the edge         int u = p.second;  // Vertex connected to the edge                  if(visited[u] == true){             continue;  // Skip if the vertex is already visited         }                  res += wt;  // Add the edge weight to the result         visited[u] = true;  // Mark the vertex as visited                  // Explore the adjacent vertices         for(auto v : adj[u]){             // v[0] represents the vertex and v[1] represents the edge weight             if(visited[v[0]] == false){                 pq.push({v[1], v[0]});  // Add the adjacent edge to the priority queue             }         }     }          return res;  // Return the sum of edge weights of the Minimum Spanning Tree }  int main() {     vector<vector<int>> graph = {{0, 1, 5},                       			{1, 2, 3},                       			{0, 2, 1}};      cout << spanningTree(3, 3, graph) << endl;      return 0; } 
Java
// A Java program for Prim's Minimum Spanning Tree (MST) // algorithm. The program is for adjacency list // representation of the graph  import java.io.*; import java.util.*;  // Class to form pair class Pair implements Comparable<Pair> {     int v;     int wt;     Pair(int v,int wt)     {         this.v=v;         this.wt=wt;     }     public int compareTo(Pair that)     {         return this.wt-that.wt;     } }  class GFG {  	// Function of spanning tree 	static int spanningTree(int V, int E, int edges[][])     {          ArrayList<ArrayList<Pair>> adj=new ArrayList<>();          for(int i=0;i<V;i++)          {              adj.add(new ArrayList<Pair>());          }          for(int i=0;i<edges.length;i++)          {              int u=edges[i][0];              int v=edges[i][1];              int wt=edges[i][2];              adj.get(u).add(new Pair(v,wt));              adj.get(v).add(new Pair(u,wt));          }          PriorityQueue<Pair> pq = new PriorityQueue<Pair>();          pq.add(new Pair(0,0));          int[] vis=new int[V];          int s=0;          while(!pq.isEmpty())          {              Pair node=pq.poll();              int v=node.v;              int wt=node.wt;              if(vis[v]==1)               continue;                            s+=wt;              vis[v]=1;              for(Pair it:adj.get(v))              {                  if(vis[it.v]==0)                  {                      pq.add(new Pair(it.v,it.wt));                  }              }          }          return s;     }          // Driver code     public static void main (String[] args) {         int graph[][] = new int[][] {{0,1,5},                                     {1,2,3},                                     {0,2,1}};           // Function call         System.out.println(spanningTree(3,3,graph));     } } 
Python
import heapq  def tree(V, E, edges):     # Create an adjacency list representation of the graph     adj = [[] for _ in range(V)]     # Fill the adjacency list with edges and their weights     for i in range(E):         u, v, wt = edges[i]         adj[u].append((v, wt))         adj[v].append((u, wt))     # Create a priority queue to store edges with their weights     pq = []     # Create a visited array to keep track of visited vertices     visited = [False] * V     # Variable to store the result (sum of edge weights)     res = 0     # Start with vertex 0     heapq.heappush(pq, (0, 0))     # Perform Prim's algorithm to find the Minimum Spanning Tree     while pq:         wt, u = heapq.heappop(pq)         if visited[u]:             continue               # Skip if the vertex is already visited         res += wt           # Add the edge weight to the result         visited[u] = True           # Mark the vertex as visited         # Explore the adjacent vertices         for v, weight in adj[u]:             if not visited[v]:                 heapq.heappush(pq, (weight, v))                   # Add the adjacent edge to the priority queue     return res     # Return the sum of edge weights of the Minimum Spanning Tree if __name__ == "__main__":     graph = [[0, 1, 5],              [1, 2, 3],              [0, 2, 1]]     # Function call     print(tree(3, 3, graph)) 
C#
using System; using System.Collections.Generic;  public class MinimumSpanningTree {     // Function to find sum of weights of edges of the Minimum Spanning Tree.     public static int SpanningTree(int V, int E, int[,] edges)     {         // Create an adjacency list representation of the graph         List<List<int[]>> adj = new List<List<int[]>>();         for (int i = 0; i < V; i++)         {             adj.Add(new List<int[]>());         }          // Fill the adjacency list with edges and their weights         for (int i = 0; i < E; i++)         {             int u = edges[i, 0];             int v = edges[i, 1];             int wt = edges[i, 2];             adj[u].Add(new int[] { v, wt });             adj[v].Add(new int[] { u, wt });         }          // Create a priority queue to store edges with their weights         PriorityQueue<(int, int)> pq = new PriorityQueue<(int, int)>();          // Create a visited array to keep track of visited vertices         bool[] visited = new bool[V];          // Variable to store the result (sum of edge weights)         int res = 0;          // Start with vertex 0         pq.Enqueue((0, 0));          // Perform Prim's algorithm to find the Minimum Spanning Tree         while (pq.Count > 0)         {             var p = pq.Dequeue();             int wt = p.Item1;  // Weight of the edge             int u = p.Item2;  // Vertex connected to the edge              if (visited[u])             {                 continue;  // Skip if the vertex is already visited             }              res += wt;  // Add the edge weight to the result             visited[u] = true;  // Mark the vertex as visited              // Explore the adjacent vertices             foreach (var v in adj[u])             {                 // v[0] represents the vertex and v[1] represents the edge weight                 if (!visited[v[0]])                 {                     pq.Enqueue((v[1], v[0]));  // Add the adjacent edge to the priority queue                 }             }         }          return res;  // Return the sum of edge weights of the Minimum Spanning Tree     }      public static void Main()     {         int[,] graph = { { 0, 1, 5 }, { 1, 2, 3 }, { 0, 2, 1 } };          // Function call         Console.WriteLine(SpanningTree(3, 3, graph));     } }  // PriorityQueue implementation for C# public class PriorityQueue<T> where T : IComparable<T> {     private List<T> heap = new List<T>();      public int Count => heap.Count;      public void Enqueue(T item)     {         heap.Add(item);         int i = heap.Count - 1;         while (i > 0)         {             int parent = (i - 1) / 2;             if (heap[parent].CompareTo(heap[i]) <= 0)                 break;              Swap(parent, i);             i = parent;         }     }      public T Dequeue()     {         int lastIndex = heap.Count - 1;         T frontItem = heap[0];         heap[0] = heap[lastIndex];         heap.RemoveAt(lastIndex);          --lastIndex;         int parent = 0;         while (true)         {             int leftChild = parent * 2 + 1;             if (leftChild > lastIndex)                 break;              int rightChild = leftChild + 1;             if (rightChild <= lastIndex && heap[leftChild].CompareTo(heap[rightChild]) > 0)                 leftChild = rightChild;              if (heap[parent].CompareTo(heap[leftChild]) <= 0)                 break;              Swap(parent, leftChild);             parent = leftChild;         }          return frontItem;     }      private void Swap(int i, int j)     {         T temp = heap[i];         heap[i] = heap[j];         heap[j] = temp;     } } 
JavaScript
class PriorityQueue {     constructor() {         this.heap = [];     }      enqueue(value) {         this.heap.push(value);         let i = this.heap.length - 1;         while (i > 0) {             let j = Math.floor((i - 1) / 2);             if (this.heap[i][0] >= this.heap[j][0]) {                 break;             }             [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];             i = j;         }     }      dequeue() {         if (this.heap.length === 0) {             throw new Error("Queue is empty");         }         let i = this.heap.length - 1;         const result = this.heap[0];         this.heap[0] = this.heap[i];         this.heap.pop();          i--;         let j = 0;         while (true) {             const left = j * 2 + 1;             if (left > i) {                 break;             }             const right = left + 1;             let k = left;             if (right <= i && this.heap[right][0] < this.heap[left][0]) {                 k = right;             }             if (this.heap[j][0] <= this.heap[k][0]) {                 break;             }             [this.heap[j], this.heap[k]] = [this.heap[k], this.heap[j]];             j = k;         }          return result;     }      get count() {         return this.heap.length;     } }  function spanningTree(V, E, edges) {     // Create an adjacency list representation of the graph     const adj = new Array(V).fill(null).map(() => []);      // Fill the adjacency list with edges and their weights     for (let i = 0; i < E; i++) {         const [u, v, wt] = edges[i];         adj[u].push([v, wt]);         adj[v].push([u, wt]);     }      // Create a priority queue to store edges with their weights     const pq = new PriorityQueue();      // Create a visited array to keep track of visited vertices     const visited = new Array(V).fill(false);      // Variable to store the result (sum of edge weights)     let res = 0;      // Start with vertex 0     pq.enqueue([0, 0]);      // Perform Prim's algorithm to find the Minimum Spanning Tree     while (pq.count > 0) {         const p = pq.dequeue();          const wt = p[0];  // Weight of the edge         const u = p[1];   // Vertex connected to the edge          if (visited[u]) {             continue;  // Skip if the vertex is already visited         }          res += wt;  // Add the edge weight to the result         visited[u] = true;  // Mark the vertex as visited          // Explore the adjacent vertices         for (const v of adj[u]) {             // v[0] represents the vertex and v[1] represents the edge weight             if (!visited[v[0]]) {                 pq.enqueue([v[1], v[0]]);  // Add the adjacent edge to the priority queue             }         }     }      return res;  // Return the sum of edge weights of the Minimum Spanning Tree }  // Example usage const graph = [[0, 1, 5], [1, 2, 3], [0, 2, 1]];  // Function call console.log(spanningTree(3, 3, graph)); 

Output
4 

Time Complexity: O((E+V)*log(V)) where V is the number of vertex and E is the number of edges
Auxiliary Space: O(E+V) where V is the number of vertex and E is the number of edges

Advantages and Disadvantages of Prim’s algorithm

Advantages:

  • Prim’s algorithm is guaranteed to find the MST in a connected, weighted graph.
  • It has a time complexity of O((E+V)*log(V)) using a binary heap or Fibonacci heap, where E is the number of edges and V is the number of vertices.
  • It is a relatively simple algorithm to understand and implement compared to some other MST algorithms.

Disadvantages:

  • Like Kruskal’s algorithm, Prim’s algorithm can be slow on dense graphs with many edges, as it requires iterating over all edges at least once.
  • Prim’s algorithm relies on a priority queue, which can take up extra memory and slow down the algorithm on very large graphs.
  • The choice of starting node can affect the MST output, which may not be desirable in some applications.

Problems based on Minimum Spanning Tree

  • Kruskal’s Algorithm for MST
  • Minimum cost to connect all cities
  • Minimum cost to provide water
  • Second Best Minimum Spanning Tree
  • Check if an edge is a part of any MST
  • Minimize count of connections


Next Article
Kruskal’s Minimum Spanning Tree (MST) Algorithm
author
kartik
Improve
Article Tags :
  • DSA
  • Graph
  • Greedy
  • Amazon
  • Cisco
  • Minimum Spanning Tree
  • Prim's Algorithm.MST
  • Samsung
Practice Tags :
  • Amazon
  • Cisco
  • Samsung
  • Graph
  • Greedy

Similar Reads

  • Discrete Mathematics Tutorial
    Discrete Mathematics is a branch of mathematics that is concerned with "discrete" mathematical structures instead of "continuous". Discrete mathematical structures include objects with distinct values like graphs, integers, logic-based statements, etc. In this tutorial, we have covered all the topic
    4 min read
  • Mathematical Logic

    • Propositional Logic
      Logic is the basis of all mathematical reasoning and all automated reasoning. The rules of logic specify the meaning of mathematical statements. These rules help us understand and reason with statements such as - [Tex]\exists~x~such~that~x~\neq~a^2~+~b^2,~where~\:x,~a,~b\in~Z[/Tex]Which in Simple En
      10 min read

    • Discrete Mathematics - Applications of Propositional Logic
      A proposition is an assertion, statement, or declarative sentence that can either be true or false but not both. For example, the sentence "Ram went to school." can either be true or false, but the case of both happening is not possible. So we can say, the sentence "Ram went to school." is a proposi
      11 min read

    • Propositional Equivalences
      Propositional equivalences are fundamental concepts in logic that allow us to simplify and manipulate logical statements. Understanding these equivalences is crucial in computer science, engineering, and mathematics, as they are used to design circuits, optimize algorithms, and prove theorems. This
      7 min read

    • Predicates and Quantifiers
      Predicates and Quantifiers are fundamental concepts in mathematical logic, essential for expressing statements and reasoning about the properties of objects within a domain. These concepts are widely used in computer science, engineering, and mathematics to formulate precise and logical statements.
      6 min read

    • Mathematics | Some Theorems on Nested Quantifiers
      Quantifiers are expressions that indicate the scope of the term to which they are attached, they are predicates. A predicate is a property the subject of the statement can have. For example, in the statement "the sum of x and y is greater than 5", the predicate 'Q' is- sum is greater than 5, and the
      6 min read

    • Rules of Inference
      Rules of Inference: Rules of inference are logical tools used to derive conclusions from premises. They form the foundation of logical reasoning, allowing us to build arguments, prove theorems, and solve problems in mathematics, computer science, and philosophy. Understanding these rules is crucial
      10 min read

    • Mathematics | Introduction to Proofs
      Mathematical proof is an argument we give logically to validate a mathematical statement. To validate a statement, we consider two things: A statement and Logical operators. A statement is either true or false but not both. Logical operators are AND, OR, NOT, If then, and If and only if. Coupled wit
      7 min read

    Sets and Relations

    • Set Theory
      Set theory is a branch of mathematics that deals with collections of objects. These collections are called sets. A set is simply a group of distinct things, like numbers, letters, or even everyday objects, that are grouped based on some common property. A set is a well-defined collection of distinct
      3 min read

    • Types Of Sets
      In mathematics, a set is defined as a well-defined collection of distinct elements that share a common property. These elements— like numbers, letters, or even other sets are listed in curly brackets "{ }" and represented by capital letters. For example, a set can include days of the week. The diffe
      13 min read

    • Irreflexive Relation on a Set
      A relation is a subset of the cartesian product of a set with another set. A relation contains ordered pairs of elements of the set it is defined on. To learn more about relations refer to the article on "Relation and their types". What is Irreflexive Relation? A relation R on a set A is called irre
      6 min read

    • Check Reflexive Relation on Set
      A relation is a subset of the cartesian product of a set with another set. A relation contains ordered pairs of elements of the set it is defined on. To learn more about relations refer to the article on "Relation and their types". What is a Reflexive Relation?A relation R on a set A is called refle
      7 min read

    • Check Transitive Relation on a Set
      A relation is a subset of the cartesian product of a set with another set. A relation contains ordered pairs of elements of the set it is defined on. To learn more about relations refer to the article on "Relation and their types". What is a Transitive Relation?A relation R on a set A is called tran
      9 min read

    • Set Operations
      A set is simply a collection of distinct objects. These objects can be numbers, letters, or even people—anything! We denote a set using curly brackets.For example: A = {1, 2, 3} Set Operations can be defined as the operations performed on two or more sets to obtain a single set containing a combinat
      11 min read

    • Types of Functions
      Functions are defined as the relations which give a particular output for a particular input value. A function has a domain and codomain (range). f(x) usually denotes a function where x is the input of the function. In general, a function is written as y = f(x). A function is a relation between two
      15 min read

    • Mathematics | Sequence, Series and Summations
      Sequences, series, and summations are fundamental concepts of mathematical analysis and it has practical applications in science, engineering, and finance. Table of Content What is Sequence?Theorems on SequencesProperties of SequencesWhat is Series?Properties of SeriesTheorems on SeriesSummation Def
      8 min read

    • Representation of Relation in Graphs and Matrices
      Understanding how to represent relations in graphs and matrices is fundamental in engineering mathematics. These representations are not only crucial for theoretical understanding but also have significant practical applications in various fields of engineering, computer science, and data analysis.
      8 min read

    • Relations in Mathematics
      Relation in Mathematics is defined as the relationship between two sets. If we are given two sets set A and set B and set A has a relation with set B then each value of set A is related to a value of set B through some unique relation. Here, set A is called the domain of the relation, and set B is c
      10 min read

    • Closure of Relations
      Closure of Relations: In mathematics, especially in the context of set theory and algebra, the closure of relations is a crucial concept. It involves extending a given relation to include additional elements based on specific properties, such as reflexivity, symmetry, and transitivity. Understanding
      7 min read

    Mathematical Induction

    • Pigeonhole Principle
      The Pigeonhole Principle is a fundamental concept in combinatorics and mathematics that states if more items are put into fewer containers than the number of items, at least one container must contain more than one item. This seemingly simple principle has profound implications and applications in v
      13 min read

    • Mathematics | Generalized PnC Set 1
      Prerequisite - PnC and Binomial Coefficients So far every problem discussed in previous articles has had sets of distinct elements, but sometimes problems may involve repeated use of elements. This article covers such problems, where elements of the set are indistinguishable (or identical or not dis
      6 min read

    • Discrete Maths | Generating Functions-Introduction and Prerequisites
      Discrete Maths | Generating Functions-Introduction and PrerequisitesPrerequisite - Combinatorics Basics, Generalized PnC Set 1, Set 2 Definition: Generating functions are used to represent sequences efficiently by coding the terms of a sequence as coefficients of powers of a variable (say) [Tex]\big
      5 min read

    • Inclusion Exclusion principle and programming applications
      Sum Rule - If a task can be done in one of n1 ways or one of n2 ways, where none of the set of n1 ways is the same as any of the set of n2 ways, then there are n1 + n2 ways to do the task. The sum-rule mentioned above states that if there are multiple sets of ways of doing a task, there shouldn’t be
      13 min read

    Boolean Algebra

    • Properties of Boolean Algebra
      The Boolean Algebra uses sets of rules for analyzing digital gates and circuits. In this article, we will be going through the Properties or Laws of the Boolean algebra. So first we will start our article by defining what are the properties of Boolean Algebra, and then we will go through what are Bo
      7 min read

    • Number of Boolean functions
      In the below article, we are going to find the number of Boolean Functions possible from the given sets of binary number. Statement-1: Suppose two sets are set 'A' = {1, 2, 3, 4, ........, n} where each number will be either '0' or '1' and hence the total number of boolean variable possible will be
      2 min read

    • Minimization of Boolean Functions
      As discussed in the "Representation of Boolean Functions" every boolean function can be expressed as a sum of minterms or a product of maxterms. Since the number of literals in such an expression is usually high, and the complexity of the digital logic gates that implement a Boolean function is dire
      3 min read

    • Linear Programming
      Linear programming is a mathematical concept that is used to find the optimal solution of the linear function. This method uses simple assumptions for optimizing the given function. Linear Programming has a huge real-world application and it is used to solve various types of problems. The term "line
      15+ min read

    Ordered Sets & Lattices

    • Elements of POSET | Maximal Element, Minimal Element, Lower and Upper Bounds
      Partially Ordered Set (POSET) is a fundamental concept in mathematics and computer science, providing a structured way to analyze and compare elements within a set. In a POSET, not every pair of elements needs to be comparable, making it a versatile tool for representing hierarchical relationships a
      11 min read

    • Partial Order Relation on a Set
      A relation is a subset of the cartesian product of a set with another set. A relation contains ordered pairs of elements of the set it is defined on. What is a Partial Order Relation? A relation R on a set A is called a partial order relation if it is Reflexive Relation: (a, a) ∈ R ∀ a ∈ A, i.e. aRa
      15 min read

    • Axiomatic Approach to Probability
      Hearing the word "probability" brings up ideas related to uncertainty or randomness. Although the concept of probability can be hard to describe formally, it helps us analyze how likely it is that a certain event will happen. This analysis helps us understand and describe many phenomena we see in re
      10 min read

    • Properties of Probability
      ProbabilityProbability is the branch of mathematics that is concerned with the chances of occurrence of events and possibilities. Further, it gives a method of measuring the probability of uncertainty and predicting events in the future by using the available information. Probability is a measure of
      14 min read

    Probability Theory

    • Mathematics | Probability Distributions Set 1 (Uniform Distribution)
      Probability distribution is a mathematical function that can be thought of as providing the probabilities of occurrence of different possible outcomes in an experiment. For instance, if the random variable X is used to denote the outcome of a coin toss ("the experiment"), then the probability distri
      3 min read

    • Mathematics | Probability Distributions Set 2 (Exponential Distribution)
      The previous article covered the basics of Probability Distributions and talked about the Uniform Probability Distribution. This article covers the Exponential Probability Distribution which is also a Continuous distribution just like Uniform Distribution. Introduction - Suppose we are posed with th
      5 min read

    • Mathematics | Probability Distributions Set 3 (Normal Distribution)
      The previous two articles introduced two Continuous Distributions: Uniform and Exponential. This article covers the Normal Probability Distribution, also a Continuous distribution, which is by far the most widely used model for continuous measurement. Introduction - Whenever a random experiment is r
      5 min read

    • Mathematics | Probability Distributions Set 5 (Poisson Distribution)
      The previous article covered the Binomial Distribution. This article talks about another Discrete Probability Distribution, the Poisson Distribution. Introduction -Suppose an event can occur several times within a given unit of time. When the total number of occurrences of the event is unknown, we c
      4 min read

    Graph Theory

    • Graph and its representations
      A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
      12 min read

    • Mathematics | Graph Theory Basics - Set 1
      A Graph is just a way to show connections between things. It is set of edges and vertices where each edge is associated with unordered pair of vertices. Graph is a data structure that is defined by two components : Node or Vertex: It is a point or joint between two lines like people, cities, or webs
      5 min read

    • Types of Graphs with Examples
      A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
      9 min read

    • Walks, Trails, Paths, Cycles and Circuits in Graph
      Walks, trails, paths, cycles, and circuits in a graph are sequences of vertices and edges with different properties. Some allow repetition of vertices and edges, while others do not. In this article, we will explore these concepts with examples. What is Walk?A walk in a graph is a sequence of vertic
      6 min read

    • Dijkstra's Algorithm to find Shortest Paths from a Source to all
      Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1. Note: The given graph does not contain any negative edge. Exampl
      12 min read

    • Prim’s Algorithm for Minimum Spanning Tree (MST)
      Prim’s algorithm is a Greedy algorithm like Kruskal's algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way. The algorithm starts with an empty spanning tree. The idea is to maintain two sets
      15+ min read

    • Kruskal’s Minimum Spanning Tree (MST) Algorithm
      A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, and undirected graph is a spanning tree (no cycles and connects all vertices) that has minimum weight. The weight of a spanning tree is the sum of all edges in the tree. In Kruskal's algorithm, we sort all edges
      9 min read

    • Check whether a given graph is Bipartite or not
      Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not. Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex
      9 min read

    • Eulerian path and circuit for undirected graph
      Eulerian Path is a path in a graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path that starts and ends on the same vertex.       How to Find Whether a Given Graph is Eulerian or not? The problem is same as following question. "Is it possible to draw a given graph without l
      15+ min read

    Special Graph

    • Introduction to Graph Coloring
      Graph coloring refers to the problem of coloring vertices of a graph in such a way that no two adjacent vertices have the same color. This is also called the vertex coloring problem. If coloring is done using at most m colors, it is called m-coloring. Chromatic Number:The minimum number of colors ne
      11 min read

    • Edge Coloring of a Graph
      In graph theory, edge coloring of a graph is an assignment of "colors" to the edges of the graph so that no two adjacent edges have the same color with an optimal number of colors. Two edges are said to be adjacent if they are connected to the same vertex. There is no known polynomial time algorithm
      9 min read

    • Check if a graph is Strongly, Unilaterally or Weakly connected
      Given an unweighted directed graph G as a path matrix, the task is to find out if the graph is Strongly Connected or Unilaterally Connected or Weakly Connected. Strongly Connected: A graph is said to be strongly connected if every pair of vertices(u, v) in the graph contains a path between each othe
      12 min read

    • Biconnected Components
      A biconnected component is a maximal biconnected subgraph. Biconnected Graph is already discussed here. In this article, we will see how to find biconnected component in a graph using algorithm by John Hopcroft and Robert Tarjan. In above graph, following are the biconnected components: 4--2 3--4 3-
      15+ min read

    • Strongly Connected Components
      Strongly Connected Components (SCCs) are a fundamental concept in graph theory and algorithms. In a directed graph, a Strongly Connected Component is a subset of vertices where every vertex in the subset is reachable from every other vertex in the same subset by traversing the directed edges. Findin
      15+ min read

    Group Theory

    • Mathematics | Graph Theory Basics - Set 1
      A Graph is just a way to show connections between things. It is set of edges and vertices where each edge is associated with unordered pair of vertices. Graph is a data structure that is defined by two components : Node or Vertex: It is a point or joint between two lines like people, cities, or webs
      5 min read

    • Homomorphism & Isomorphism of Group
      We can say that  "o" is the binary operation on set G if: G is a non-empty set & G * G = { (a,b) : a , b∈ G } and o : G * G --> G. Here, aob denotes the image of ordered pair (a,b) under the function/operation o. Example - "+" is called a binary operation on G (any non-empty set ) if & on
      7 min read

    • Group Isomorphisms and Automorphisms
      In the study of algebraic structures, group isomorphisms and automorphisms play a fundamental role. By defining internal symmetries inside a group (automorphisms) and when two groups have the same structure (isomorphisms), these ideas aid in our understanding of the structure and symmetry of groups.
      7 min read

    • Group in Maths: Group Theory
      Group theory is one of the most important branches of abstract algebra which is concerned with the concept of the group. A group consists of a set equipped with a binary operation that satisfies four key properties: specifically, it includes property of closure, associativity, the existence of an id
      13 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences