Data Structures & Algorithms (Graph): Dijkstra's Algorithm

April 15, 2026

Dijkstra's Algorithm is a graph traversal algorithm used to find the shortest path from a source node to all other nodes in a weighted graph, provided all edge weights are non-negative.

Example: Travelling Between Countries

Imagine you are travelling between different countries and want to find the minimum time required to travel from India to every other country.

🇮🇳 India0h🇦🇪 UAE∞🇸🇬 Singapore∞🇬🇧 UK∞🇺🇸 USA∞3h5h11h7h9h17h8h
SetupFind the shortest flight time from India. Start India at 0h and every other country at ∞.
1/14

Key Observations

  1. Out of all the nodes whose shortest path are not yet confirmed, we can pick the node with the smallest known distance from the source. Any alternative path to this node must pass through another unprocessed node. Since all edge weights are non-negative, that path cannot produce a shorter distance than the one we have already found.

  2. Once we know the shortest path of a node from the source, we can explore its neighbours and attempt to improve their shortest known distances.


Algorithm

The algorithm uses a greedy approach combined with a min-priority queue to always process the node with the smallest known distance from the source. By repeatedly exploring its neighbours and relaxing edges, we gradually determine the shortest paths to all reachable nodes.

Let's understand the algorithm through the following questions.

Q1. How do we start?

We start from the source node with an initial distance of 0. Initialize the distance of all other nodes to infinity.

algorithm-1

Q2. What do we do after initializing the distances?

We explore all the neighbours of the source node and update their shortest known distances based on the corresponding edge weights.

algorithm-2

Q3. How do we store the unprocessed nodes?

We use a min-priority queue to store the discovered nodes along with their shortest known distances from the source.

algorithm-3

Q4. How do we decide which node to process next?

We extract the node with the smallest known distance from the priority queue. This ensures that we always process the closest unprocessed node first.

algorithm-4

Q5. What happens when we process a node?

We explore all its neighbours and attempt to improve their shortest known distances by relaxing the edges.

For every neighbour, we calculate: newDistance = dist[currentNode] + edgeWeight. If the newly calculated distance is smaller than the existing distance, we update it and insert the updated entry into the priority queue.

algorithm-5

Q6. How do we continue the process?

We repeat the same process:

1. Extract the node with the smallest known distance.
2. Explore its neighbours.
3. Relax the edges and update distances if a shorter path is found.
4. Insert the updated entries into the priority queue.

We continue until the priority queue becomes empty.

Q7. What is the final result?

At the end, the distance array contains the shortest distance from the source node to every reachable node.

algorithm-6

Note

Nodes that remain unreachable retain an infinite distance.


Implementation

Most DSA problems represent a graph using an array of edges where each entry represents: {source, destination, weight}.

An Edge List is a convenient way to provide the graph as input because we only need to specify the existing connections. However, it does not provide an efficient way to explore the neighbours of a particular node.

To find the neighbours of a node, we would have to iterate over the entire Edge List and identify all edges connected to that node. Since Dijkstra frequently explores the neighbours of the currently extracted node, repeatedly scanning the entire Edge List introduces unnecessary overhead.

0/8 rows read

edges = [
  1. 0[0, 1, 4],
  2. 1[0, 2, 1],
  3. 2[1, 2, 2],
  4. 3[3, 4, 5],
  5. 4[1, 4, 6],
  6. 5[2, 4, 3],
  7. 6[3, 5, 2],
  8. 7[4, 5, 1]
]
01234541256321

Each inner array is one edge. Neighbours of 3 are not grouped.

Therefore, we convert the Edge List into an Adjacency List, which maintains the neighbours of each node along with their corresponding edge weights.

Language
1public int[] dijkstra(int n, int[][] edges, int source) {
2
3 // Step 1: Build the adjacency list.
4 List<int[]>[] graph = new ArrayList[n];
5
6 for (int i = 0; i < n; i++) {
7 graph[i] = new ArrayList<>();
8 }
9
10 // Add edges to the adjacency list.
11 for (int[] edge: edges) {
12
13 int u = edge[0];
14 int v = edge[1];
15 int weight = edge[2];
16
17 graph[u].add(new int[]{v, weight});
18 // If the graph is undirected, add both directions.
19 graph[v].add(new int[]{u, weight});
20 }
21
22 // Step 2: Initialize the distance array.
23 int[] dist = new int[n];
24 // Initially, all nodes are unreachable (infinity).
25 Arrays.fill(dist, Integer.MAX_VALUE);
26
27 // Distance from the source to iteself is 0.
28 dist[source] = 0;
29
30 // Step 3: Create a min-priority queue.
31 PriorityQueue<int[]> pq = new PriorityQueue<>(
32 Comparator.comparingInt(a -> a[0])
33 );
34
35 // Add the source node with distance 0.
36 pf.offer(new int[]{0, source});
37
38 // Step 4: Process the nodes until the priority queue is empty.
39 while (!pq.empty()) {
40
41 // Extract the node with the smallest node distance.
42 int[] current = pq.poll();
43
44 int distance = current[0];
45 int node = current[1];
46
47 // Step 5: Skip outdates entries.
48 // A better distance might have been discovered
49 // after this entry was inserted into the queue.
50 if (distance > dist[node]) {
51 continue;
52 }
53
54 // Step 6: Explore all neighbours of the current node.
55 for (int[] neighbour : graph[node] ) {
56
57 int nextNode = neighbour[0];
58 int weight = neighbour[1];
59
60 // Calculate the distance to the neighbour
61 // through the current node.
62 int newDistance = distance + weight;
63
64 // Step 7: Relax the edge.
65 // Update the distance if we discover a shorter path.
66 if (newDistance < dist[nextNode]) {
67
68 dist[node] = newDistance;
69
70 // Insert the updated distance into the min-heap.
71 pq.offer(new int[]{newDistance, nextNode});
72 }
73 }
74 }
75
76 // Step 8: Return the shortest distances.
77 // Convert unreachable nodes from INF to -1.
78 for (int i = 0; i < n; i++) {
79
80 if (dist[i] == Integer.MAX_VALUE) {
81 dist[i] = -1;
82 }
83 }
84
85 return dist;
86}
Input
41256321012345
dist
not created
pq
empty
graph
not created

Call dijkstra with n = 6 and source = 0.

1/46


Time Complexity

The time complexity of Dijkstra's Algorithm can be broken down into four major operations:

  1. Building the Adjacency List: We iterate over all vertices (V) to initialize their adjacency lists and iterate over all edges (E) to populate them. This operation takes O(V + E).

  2. Adding nodes to the Priority Queue: Whenever we discover a shorter path to a neighbouring node, we insert an updated entry into the priority queue. Every successful relaxation corresponds to examining a particular edge. Hence, the number of successful relaxations is bounded by (E). Considering each insertion into a binary min-heap takes O(V) time, the total node addition is O(E * logV).

  3. Removing nodes from the Priority Queue: Since there can be at most (E) successful relaxations, there can be at most (E) extractions. Considering each extraction takes O(logV) time, the total node removal is O(E * logV).

  4. Exploring the neighbours of a node: Since each vertex is processed at most once, and all its adjacency entries are examined once, the total neighbour traversal is O(V + E).

Combining all four operations, the overall time complexity is O(V + E) + O(E * logV) + O(E * logV) + O(V + E) = O(V + E + E * logV) ~ O(E * logV).


Space Complexity

Let's break it down into the different data structures we maintain.

  1. Adjacency List: Every vertex has an adjacency list, requiring O(V) space. Every edge is stored in the adjacency list. Therefore, this takes O(V + E).

  2. Distance array: We maintain a dist[] array to store the shortest known distance from the source to every vertex. Since there are (V) vertices, the array requires O(V).

  3. Priority queue: Since each successful relaxation can result in one insertion, and there are at most O(E) successful relaxations, the priority queue can contain up to O(E) entries.

Therefore, the overall space complexity is O(V+E).