What is Dijkstra's algorithm?

Why Interviewers Ask This

This tests whether you can apply Data Structures & Algorithms knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

Dijkstra's algorithm finds the shortest path from a source vertex to all other vertices in a weighted graph with non-negative edge weights. Algorithm: (1) Initialize distances: source = 0, all others = ∞; (2) Use a min-priority queue; add source; (3) While queue not empty: extract minimum distance vertex u; for each neighbor v: if dist[u] + weight(u,v) < dist[v], update dist[v] and add v to queue (or decrease key). Time: O((V+E) log V) with binary heap, O(V²) with array (for dense graphs). Space: O(V). Greedy algorithm — always expands the closest unvisited vertex. Correctness: guaranteed optimal because all edge weights ≥ 0, so once a node is finalized, its shortest path is found. Fails with negative weights: use Bellman-Ford instead. Variants: find shortest path to a specific target (stop early when target is extracted), bidirectional Dijkstra (start from source and target simultaneously — faster). Applications: (1) GPS navigation — shortest route between locations; (2) Network routing protocols (OSPF); (3) Game AI pathfinding; (4) Social network closest connection. A* algorithm: Dijkstra + heuristic to guide search direction — faster for single-target in spatial graphs.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Data Structures & Algorithms answers easy to follow.