Data Structures & Algorithms

Prim's Algorithm

Ace your coding interviews by mastering Prim's algorithm for Minimum Spanning Trees (MST). Our guide covers its greedy strategy, implementation with priority queues, and offers AI-powered practice.

Prim's Algorithm Implementation

Here is a Python implementation of Prim's algorithm using a priority queue (min-heap) to find the MST of a graph.

import heapqdefprims(graph, start_node): mst = [] visited = set([start_node]) edges = [ (weight, start_node, to_node)for to_node, weight in graph[start_node].items() ] heapq.heapify(edges) total_weight = 0while edges: weight, from_node, to_node = heapq.heappop(edges)if to_node not in visited: visited.add(to_node) mst.append((from_node, to_node, weight)) total_weight += weightfor next_node, next_weight in graph[to_node].items():if next_node not in visited: heapq.heappush(edges, (next_weight, to_node, next_node))return mst, total_weight

AI Coach Tip: Prim's algorithm is conceptually similar to Dijkstra's. Both use a priority queue to greedily select the next vertex. The key difference is the value stored in the priority queue: Prim's prioritizes the minimum edge weight to an unvisited neighbor, while Dijkstra's prioritizes the minimum total distance from the source.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Case Study Presentation Interview Tips
AI-powered interview preparation guide
Professional Conduct Interview Questions
AI-powered interview preparation guide
Online Interview Connection Stability Guide
AI-powered interview preparation guide
Trie Data Structure Applications In Interviews
AI-powered interview preparation guide