DSA Explorer
QuicksortMerge SortBubble SortInsertion SortSelection SortHeap SortCounting SortRadix SortBucket SortShell SortTim SortCocktail Shaker SortComb SortGnome SortPancake SortPatience SortCycle SortStrand SortWiggle Sort (Wave Sort)Bead Sort (Gravity Sort)Binary Insertion SortBitonic SortBogo Sort (Stupid Sort)Stooge SortOdd-Even Sort (Brick Sort)Pigeonhole SortIntro Sort (Introspective Sort)Tree Sort (BST Sort)Dutch National Flag (3-Way Partitioning)
Binary SearchLinear SearchJump SearchInterpolation SearchExponential SearchTernary SearchFibonacci SearchQuick Select (k-th Smallest)Median of Medians (Deterministic Select)Hill climbingSimulated AnnealingTabu SearchBinary Tree DFS SearchSentinel Linear SearchDouble Linear SearchTernary Search (Unimodal Function)Search in 2D Matrix
Binary Search Tree (BST)StackQueueHash Table (Hash Map)Heap (Priority Queue)Linked ListTrie (Prefix Tree)Binary TreeTrie (Prefix Tree)Floyd's Cycle Detection (Tortoise and Hare)Merge Two Sorted Linked ListsCheck if Linked List is PalindromeFind Middle of Linked ListBalanced Parentheses (Valid Parentheses)Next Greater ElementInfix to Postfix ConversionMin Stack (O(1) getMin)Largest Rectangle in HistogramDaily Temperatures (Monotonic Stack)Evaluate Reverse Polish NotationInfix Expression Evaluation (Two Stacks)Min Heap & Max HeapSliding Window MaximumTrapping Rain WaterRotate Matrix 90 DegreesSpiral Matrix TraversalSet Matrix ZeroesHash Table with ChainingOpen Addressing (Linear Probing)Double HashingCuckoo Hashing
Depth-First Search (DFS)Breadth-First Search (BFS)Dijkstra's AlgorithmFloyd-Warshall AlgorithmKruskal's AlgorithmPrim's AlgorithmTopological SortA* Pathfinding AlgorithmKahn's Algorithm (Topological Sort)Ford-Fulkerson Max FlowEulerian Path/CircuitBipartite Graph CheckBorůvka's Algorithm (MST)Bidirectional DijkstraPageRank AlgorithmBellman-Ford AlgorithmTarjan's Strongly Connected ComponentsArticulation Points (Cut Vertices)Find Bridges (Cut Edges)Articulation Points (Cut Vertices)Finding Bridges (Cut Edges)
0/1 Knapsack ProblemLongest Common Subsequence (LCS)Edit Distance (Levenshtein Distance)Longest Increasing Subsequence (LIS)Coin Change ProblemFibonacci Sequence (DP)Matrix Chain MultiplicationRod Cutting ProblemPalindrome Partitioning (Min Cuts)Subset Sum ProblemWord Break ProblemLongest Palindromic SubsequenceMaximal Square in MatrixInterleaving StringEgg Drop ProblemUnique Paths in GridCoin Change II (Count Ways)Decode WaysWildcard Pattern MatchingRegular Expression MatchingDistinct SubsequencesMaximum Product SubarrayHouse RobberClimbing StairsPartition Equal Subset SumKadane's Algorithm (Maximum Subarray)
A* Search AlgorithmConvex Hull (Graham Scan)Line Segment IntersectionCaesar CipherVigenère CipherRSA EncryptionHuffman CompressionRun-Length Encoding (RLE)Lempel-Ziv-Welch (LZW)Canny Edge DetectionGaussian Blur FilterSobel Edge FilterHarris Corner DetectionHistogram EqualizationMedian FilterLaplacian FilterMorphological ErosionMorphological DilationImage Thresholding (Otsu's Method)Conway's Game of LifeLangton's AntRule 30 Cellular AutomatonFast Fourier Transform (FFT)Butterworth FilterSpectrogram (STFT)
Knuth-Morris-Pratt (KMP) AlgorithmRabin-Karp AlgorithmBoyer-Moore AlgorithmAho-Corasick AlgorithmManacher's AlgorithmSuffix ArraySuffix Tree (Ukkonen's Algorithm)Trie for String MatchingEdit Distance for StringsLCS for String MatchingHamming DistanceJaro-Winkler DistanceDamerau-Levenshtein DistanceBitap Algorithm (Shift-Or, Baeza-Yates-Gonnet)Rolling Hash (Rabin-Karp Hash)Manacher's AlgorithmZ AlgorithmLevenshtein Distance

Prim's Algorithm

Graph
O((V + E) log V) time, O(V) space
Intermediate

Minimum Spanning Tree algorithm that grows MST from starting vertex. Uses priority queue for efficiency. Named after Robert Prim, it builds MST by starting from arbitrary vertex and repeatedly adding minimum weight edge that connects MST to a new vertex.

Prerequisites:
Priority queues
Greedy algorithms
MST concepts

Visualization

Interactive visualization for Prim's Algorithm

Prim's MST Algorithm

• Time: O(E log V) with binary heap

• Greedy algorithm

• Grows MST from single vertex

Interactive visualization with step-by-step execution

Implementation

Language:
1function prim(graph: number[][][], start: number = 0): [number, number, number][] {
2  const n = graph.length;
3  const visited = new Array(n).fill(false);
4  const mst: [number, number, number][] = [];
5  const pq: [number, number, number][] = []; // [weight, from, to]
6  
7  visited[start] = true;
8  for (const [v, weight] of graph[start]) {
9    pq.push([weight, start, v]);
10  }
11  
12  pq.sort((a, b) => a[0] - b[0]);
13  
14  while (pq.length > 0 && mst.length < n - 1) {
15    const [weight, u, v] = pq.shift()!;
16    
17    if (visited[v]) continue;
18    
19    visited[v] = true;
20    mst.push([u, v, weight]);
21    
22    for (const [next, w] of graph[v]) {
23      if (!visited[next]) {
24        pq.push([w, v, next]);
25        pq.sort((a, b) => a[0] - b[0]);
26      }
27    }
28  }
29  
30  return mst;
31}

Deep Dive

Theoretical Foundation

Prim's algorithm builds MST by starting with arbitrary vertex and growing the tree one vertex at a time. Maintains a cut between vertices in MST and vertices not yet included. Always selects minimum weight edge crossing this cut. Uses priority queue to efficiently find minimum weight edge. Unlike Kruskal which considers all edges globally, Prim works locally from current MST. Time: O((V + E) log V) with binary heap, O(V²) with simple array, O(E + V log V) with Fibonacci heap.

Complexity

Time

Best

O((V + E) log V)

Average

O((V + E) log V)

Worst

O((V + E) log V)

Space

Required

O(V)

Applications

Industry Use

1

Network design (telecommunications, computer networks)

2

Cable laying (minimize total cable length)

3

Circuit board design (minimize wire length)

4

Cluster analysis (minimum spanning tree clustering)

5

Approximation algorithms for TSP

6

Image segmentation and computer vision

7

Social network analysis

Use Cases

Minimum Spanning Tree
Network design
Cable laying

Related Algorithms

Depth-First Search (DFS)

Graph traversal exploring as deep as possible before backtracking. DFS is a fundamental algorithm that uses a stack (either implicitly through recursion or explicitly) to explore graph vertices. It's essential for cycle detection, topological sorting, and pathfinding problems.

Graph

Breadth-First Search (BFS)

Level-by-level graph traversal guaranteeing shortest paths in unweighted graphs. BFS uses a queue to explore vertices level by level, making it optimal for finding shortest paths and solving problems that require exploring nearest neighbors first.

Graph

Dijkstra's Algorithm

Finds shortest path from source to all vertices in weighted graph with non-negative edges. Uses greedy approach with priority queue.

Graph

Floyd-Warshall Algorithm

Floyd-Warshall is an all-pairs shortest path algorithm that finds shortest distances between every pair of vertices in a weighted graph. Unlike Dijkstra (single-source), it computes shortest paths from all vertices to all other vertices simultaneously. The algorithm can handle negative edge weights but not negative cycles. Developed independently by Robert Floyd, Bernard Roy, and Stephen Warshall in the early 1960s.

Graph
DSA Explorer

Master Data Structures and Algorithms through interactive visualizations and detailed explanations. Our platform helps you understand complex concepts with clear examples and real-world applications.

Quick Links

  • About DSA Explorer
  • All Algorithms
  • Data Structures
  • Contact Support

Legal

  • Privacy Policy
  • Terms of Service
  • Cookie Policy
  • Code of Conduct

Stay Updated

Subscribe to our newsletter for the latest algorithm explanations, coding challenges, and platform updates.

We respect your privacy. Unsubscribe at any time.

© 2026 Momin Studio. All rights reserved.

SitemapAccessibility
v1.0.0