Back to Practice Dashboard
DSA SectionEasy

Prim

Learn how to solve the 'Prim' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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.

Constraints
  • 1 <= V <= 500
  • 0 <= E <= 1000

Examples

Example 1
Input
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}}
Output
16
Explanation

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?
Represent graph node connections as an adjacency list/matrix, then use standard BFS or DFS graph traversal.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor