Prim
Detailed guide and Python implementation for the 'Prim' problem.
1. Concept Overview
The 'Prim' problem is a key challenge in the Graphs section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Prim.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Prim carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
Write a function prim_mst(graph) that takes an undirected, connected, weighted graph represented as an adjacency list of dictionaries (where graph[u][v] is the weight of edge (u, v)) and returns the sum of weights of the Minimum Spanning Tree (MST) using Prim's algorithm.
- •1 <= V <= 500
- •0 <= E <= 1000
Examples
graph = {0: {1: 2, 3: 6}, 1: {0: 2, 2: 3, 3: 8, 4: 5}, 2: {1: 3, 4: 7}, 3: {0: 6, 1: 8, 4: 9}, 4: {1: 5, 2: 7, 3: 9}}16
MST edges selected are: (0,1) wt 2, (1,2) wt 3, (1,4) wt 5, (0,3) wt 6. Total weight = 16.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def prim_opt(graph, start):
return prim_brute(graph, start)Brute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
import heapq
def prim_brute(graph, start):
mst = []
visited = {start}
edges = [(weight, start, to) for to, weight in graph[start].items()]
heapq.heapify(edges)
while edges:
weight, frm, to = heapq.heappop(edges)
if to not in visited:
visited.add(to)
mst.append((frm, to, weight))
for next_to, next_weight in graph[to].items():
if next_to not in visited:
heapq.heappush(edges, (next_weight, to, next_to))
return mstAlgorithm Pattern Checklist
When dealing with Graphs data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.