Skip to main content

Graph Algorithms

Essential graph algorithms for interviews — shortest paths, MST, and connectivity.

Shortest Path Algorithms

Dijkstra’s Algorithm

Finds shortest paths from a source to all vertices in a weighted graph with non-negative edges.
  • Time: O((V + E) log V) with min-heap
  • Cannot handle negative edges

Bellman-Ford Algorithm

Handles negative edge weights and detects negative cycles.
  • Time: O(V × E)

Floyd-Warshall Algorithm

All-pairs shortest paths using DP.
  • Time: O(V³), Space: O(V²)
  • Works with negative edges (no negative cycles)

Comparison

Minimum Spanning Tree

Kruskal’s Algorithm

Greedy approach — sort edges by weight, add if no cycle (using Union-Find).
  • Time: O(E log E)
  • Best for sparse graphs

Prim’s Algorithm

Greedy approach — grow MST from a starting vertex using a min-heap.
  • Time: O((V + E) log V)
  • Best for dense graphs

Strongly Connected Components

Kosaraju’s Algorithm

  1. Run DFS and record finish order
  2. Transpose the graph
  3. Run DFS on transposed graph in reverse finish order
  • Time: O(V + E)

Tarjan’s Algorithm

Single-pass DFS using discovery time and low-link values.
  • Time: O(V + E)
  • Also finds bridges and articulation points

Bridges & Articulation Points

  • Bridge: edge whose removal disconnects the graph
  • Articulation Point: vertex whose removal disconnects the graph
  • Found using Tarjan’s low-link values

Classic Problems

  • Network Delay Time (Dijkstra)
  • Cheapest Flights Within K Stops (Bellman-Ford)
  • Min Cost to Connect All Points (Prim/Kruskal)
  • Critical Connections in a Network (bridges)
  • Course Schedule (topological sort)
  • Path with Maximum Probability
  • Swim in Rising Water