Dijkstra’s Algorithm Explained: Worked Example, Complexity and Exam Traps
Build Dijkstra’s algorithm from its core invariant, trace every relaxation on a six-vertex graph, and learn exactly where the method works and fails.
KnowledgeGate Team
Exam prep & CS education

Most aspirants remember one line about Dijkstra’s algorithm: pick the nearest vertex. The trouble begins when a later relaxation reveals a shorter route and the distance table starts changing. Dijkstra’s algorithm relies on a greedy invariant, a weighted-graph trace, and careful handling of failure cases and exam traps.
What Dijkstra’s algorithm solves
Dijkstra’s algorithm takes a directed or undirected graph , source , and weights . It finds the shortest distance from to every reachable vertex.
For each vertex , it maintains:
d[v], the best distance from found so farparent[v], the predecessor that produced that distancea settled or unsettled status
Relaxing an edge means applying d[v] = min(d[v], d[u] + w(u,v)). If the candidate is strictly smaller, both d[v] and parent[v] change.
The final parents form a tree that reconstructs each path. Unreachable vertices remain at infinity. Zero-weight edges are valid, but negative-weight edges are not.
BFS handles unweighted or unit-weight shortest paths; Dijkstra handles non-negative weights. That boundary determines which traversal belongs in a shortest-path solution.
Why the greedy choice is safe
The key invariant is simple: when the unsettled vertex with the smallest tentative distance is extracted, that distance is final.
Suppose a shorter path to the extracted vertex exists. Let be the first unsettled vertex on that path, with settled predecessor . When was settled, the edge to was relaxed. Since the remaining edges are non-negative, d[x] cannot exceed the claimed shorter path length to . Then , not , should be the minimum, a contradiction.
This is the safe local choice behind Dijkstra’s method. The same habit of proving why a local choice cannot damage the global answer appears in Greedy Algorithms: Strategy and Problems.
Worked example: trace every relaxation from S
Use this directed graph:
S->A (4), S->B (2), B->A (1), A->C (5), B->C (8), B->D (10), A->D (9), C->D (2), C->E (6), D->E (3).
Start with d[S]=0. Every other distance is infinity, and every parent is null. At each step, settle the smallest tentative vertex and relax only its outgoing edges.
Step | Vertex settled | d[A] | d[B] | d[C] | d[D] | d[E] | Parent changes |
|---|---|---|---|---|---|---|---|
Initialise | none | infinity | infinity | infinity | infinity | infinity | none |
Relax from S | S at 0 | 4 | 2 | infinity | infinity | infinity |
|
Relax from B | B at 2 | 3 | 2 | 10 | 12 | infinity |
|
Relax from A | A at 3 | 3 | 2 | 8 | 12 | infinity |
|
Relax from C | C at 8 | 3 | 2 | 8 | 10 | 14 |
|
Relax from D | D at 10 | 3 | 2 | 8 | 10 | 13 |
|
Finish | E at 13 | 3 | 2 | 8 | 10 | 13 | none |
The changes come from direct arithmetic. Through B, A improves from 4 to . Through A, C improves from 10 to . The candidate for D is , equal to its existing value, so no parent change is required. Through C, D becomes and E becomes . Through D, E finally becomes .
The final distances are S=0, B=2, A=3, C=8, D=10, E=13. The final tree edges are S->B, B->A, A->C, C->D, and D->E. Therefore the paths are S->B, S->B->A, S->B->A->C, S->B->A->C->D, and S->B->A->C->D->E. An equal-cost relaxation need not replace a parent unless a tie rule is supplied.

From the trace to an implementation
With an adjacency list and a min-priority queue, the language-neutral procedure is:
for each vertex v:
d[v] = infinity
parent[v] = null
d[S] = 0
push (0, S)
while the queue is not empty:
(du, u) = pop minimum
if du != d[u]:
continue
for each outgoing edge (u, v, w):
if d[u] + w < d[v]:
d[v] = d[u] + w
parent[v] = u
push (d[v], v)Without decrease-key, every improvement pushes a fresh pair, leaving older, larger pairs in the heap. The du != d[u] check skips these stale entries. Discovery is not settlement because a better route may appear before minimum extraction.
An adjacency list with a binary heap takes O((V+E) log V) time and O(V+E) space for the graph and algorithm state. An adjacency matrix with a linear scan for the next minimum takes O(V^2) time. A complexity bound is meaningful only with its representation and minimum-selection method.
Traps, ties and the negative-edge failure
Consider S->A (2), S->B (5), B->A (-10), and A->T (2). Dijkstra settles A at 2 and then T at 4 before reaching B. But the path S->B->A costs , and S->B->A->T costs . The negative edge creates a cheaper route to an already settled vertex, so the invariant fails.
Use Bellman-Ford when negative weights may occur. If a reachable negative cycle can affect a vertex, no finite shortest path exists for that vertex.

Keep these distinctions clear:
A zero-weight edge is not a negative edge.
Disconnected vertices remain at infinity.
Parallel edges are relaxed independently.
A directed edge cannot be followed backwards.
Equal tentative distances may produce different but equally valid predecessor trees.
Fixed-width integer code should guard against adding a weight to infinity.
Final shortest distances can be unique even when the extraction order or predecessor tree is not. This occurs when equal tentative distances exist and no tie-breaking rule is specified.
How exams turn Dijkstra into questions
Typical questions ask you to complete a tentative-distance table, choose the next settled vertex, recover the shortest-path tree, recompute after one edge changes, select the correct representation-dependent complexity, or choose among BFS, Dijkstra, Bellman-Ford and Floyd-Warshall. In computer networks, Dijkstra also appears inside link-state routing.
Use this 30-second check:
Scan for any negative edge.
Write infinity for every non-source vertex.
After each extraction, relax only outgoing edges.
Record a parent only on strict improvement unless a tie rule is stated.
Stop early only when the requested destination has just been settled.
For question-by-question practice, work through 12 solved items and answer explanations in Dijkstra's Algorithm MCQs. The six-vertex trace, invariant proof, implementation, and negative-edge counterexample above provide the deeper derivation behind those drills. Use the GATE Test Series for timed work, then place the topic inside the broader preparation path through the GATE course category.
The short version and the next drill
Dijkstra requires non-negative edge weights.
The minimum tentative vertex becomes final when extracted.
Relaxation can improve unsettled neighbours and their parents.
A binary-heap implementation takes
O((V+E) log V)time.Negative edges require a different algorithm.
Now change only C->D from 2 to 5 in the worked graph. Recompute every distance before reading further.
Pause, then check: A=3, B=2, C=8, D=12, E=14. D can keep the route through B with cost , while E is best through C with cost .
Retrace both versions without notes. Then continue through the structured algorithms sequence in GATE Guidance by Sanchit Sir.
Keep learning
Dijkstra's Algorithm Interview Questions and Answers: Traces, Complexity, and Edge Cases
Learn to explain, trace, and code Dijkstra's algorithm at a whiteboard. Includes correctness, complexity, path recovery, stale heap entries, and edge cases.
Dijkstra's Algorithm MCQs: 12 Solved Questions with Explanations
Solve 12 Dijkstra's algorithm MCQs covering the core idea, a full trace, failure cases, complexity choices and the unweighted special case.
Multi-Topic Algorithm Problems Explained: Greedy, DP and Complexity in One Worked Example
Use one four-item 0/1 knapsack instance to separate modelling, greedy output, DP optimality, proof and pseudo-polynomial complexity.
Prim's Algorithm and Minimum Spanning Tree: Worked Example, Complexity and Exam Traps
Learn what makes Prim's greedy choice safe, trace every key update on a six-vertex graph, and avoid the mistakes that derail MST questions.





