Dijkstra’s Shortest Path Algorithm

💡Strategies for Solving This Problem

Understanding Dijkstra's Algorithm

Dijkstra's algorithm finds the shortest path from a source node to all other nodes in a weighted graph with non-negative edge weights. It's one of the most important graph algorithms in computer science and appears frequently in technical interviews.

When to Use Dijkstra's

  • Shortest path problems: GPS navigation, network routing
  • Non-negative weights only: Cannot handle negative edges (use Bellman-Ford instead)
  • Single source: Find shortest paths from one node to all others
  • Directed or undirected graphs

Key Concept: Greedy Approach

Dijkstra's is a greedy algorithm that always selects the unvisited node with the smallest known distance, then explores its neighbors to update their distances.

Algorithm Steps

  1. Initialize distances: source = 0, all others = infinity
  2. Use min-heap to track unvisited nodes by distance
  3. Repeat until heap is empty:
    • Extract node u with minimum distance
    • For each neighbor v of u:
      • If distance[u] + weight(u,v) < distance[v]:
      • Update distance[v]
      • Add/update v in heap

Why It Works

Invariant: Once a node is extracted from the min-heap, we've found its shortest path from source.

Proof sketch: Since all edges are non-negative, any alternate path through unvisited nodes would have distance ≥ current distance.

Time Complexity

  • With min-heap (binary): O((V + E) log V)
  • With Fibonacci heap: O(E + V log V) - optimal
  • Without heap (array): O(V²) - better for dense graphs

Comparison with Other Algorithms

  • BFS: O(V + E) but only for unweighted graphs
  • Bellman-Ford: O(VE) but handles negative weights
  • Floyd-Warshall: O(V³) but finds all-pairs shortest paths

Common Interview Questions

  • Network Delay Time (LeetCode 743): Find time for signal to reach all nodes
  • Cheapest Flights Within K Stops (LeetCode 787): Shortest path with constraints
  • Path With Minimum Effort (LeetCode 1631): Modified Dijkstra's
  • Swim in Rising Water (LeetCode 778): Binary search + Dijkstra's

Asked at: Google, Amazon, Facebook, Microsoft, Uber, Lyft

Scroll to Top