Data Structures & Algorithms (Graphs): Single-Source Shortest Path Algorithms

April 16, 2026

Imagine you are standing at Connaught Place in Delhi, and you open Google Maps. You want to find the shortest travel distance from your current location to different locations across Delhi.

Janpath, 0.7 kmJanpath, 0.8 kmJanpath, 0.4 kmJanpath, 0.4 kmKartavya Path, 0.4 kmKartavya Path, 0.5 kmPusa Road, 2.1 kmPusa Road, 2.7 kmChelmsford Road, 1.1 kmChelmsford Road, 1.1 kmQutub Road, 0.6 kmQutub Road, 0.6 kmS.P. Mukherjee Marg, 2.4 kmChandni Chowk, 1.3 kmBarakhamba Road, 0.8 kmSikandra Road, 1.0 kmBahadur Shah Zafar Marg, 2.1 kmMahatma Gandhi Marg, 1.5 kmMahatma Gandhi Marg, 1.8 kmDB Gupta Road, 2.2 kmBhavbhuti Marg, 1.4 kmBhavbhuti Marg, 1.5 kmTolstoy Marg, 0.9 kmCopernicus Marg, 1.7 kmTilak Marg, 2.4 kmNetaji Subhash Marg, 2.7 kmJawaharlal Nehru Marg, 2.2 kmBaba Kharak Singh Marg, 1.4 kmAshoka Road, 1.2 kmPrithviraj Road, 0.8 kmDr. Zakir Hussain Marg, 1.4 kmBhairon Marg, 1.1 kmRing Road, 1.6 kmUrdu Bazaar, 0.6 kmEsplanade Road, 1.2 kmPusa Road, 1.3 kmFaiz Road, 1.7 kmPusa Road, 2.2 kmTalkatora Road, 1.1 kmRafi Marg, 2.0 kmMother Teresa Crescent, 1.6 kmRani Jhansi Marg, 1.5 kmKamla Market Road, 0.5 kmQutub Road, 0.4 kmMaulana Azad Road, 0.5 kmLothian Road, 1.9 kmLodhi Road, 1.2 km0.7 km0.8 km0.4 km0.4 km0.4 km0.5 km2.1 km2.7 km1.1 km1.1 km0.6 km0.6 km2.4 km1.3 km0.8 km1.0 km2.1 km1.5 km1.8 km2.2 km1.4 km1.5 km0.9 km1.7 km2.4 km2.7 km2.2 km1.4 km1.2 km0.8 km1.4 km1.1 km1.6 km0.6 km1.2 km1.3 km1.7 km2.2 km1.1 km2.0 km1.6 km1.5 km0.5 km0.4 km0.5 km1.9 km1.2 kmKarol BaghPatel NagarJhandewalanSadar BazarKashmere GateKamla MarketTalkatoraRashtrapatiBhavanRajendra PlacePaharganjRam NagarNew DelhiRailway StationAjmeri GateChandni ChowkRed FortConnaught PlaceSTARTBarakhambaMandi HouseITODelhi GateJantar MantarWindsor PlaceUdyog BhawanNational MuseumJaipur HouseIndia GateBangla SahibKhan MarketPragatiMaidanJama MasjidLodhi GardenNirman BhawanRamlila Maidan

Single Source Shortest Path (SSSP) algorithms are the solution to this problem. They let you find the shortest distance from a given source vertex to every other vertex in a graph.

Let's explore a few possible variations and understand how their approaches differ.


Naive Approach: Bellmand-Ford Algorithm

Bellman-Ford guarantees that one complete pass through all the edges of the graph, performing edge relaxation on each edge, discovers shortest paths containing at most one additional edge. This guarantee is based on the following two important observations:

  1. Optimal Substructure Property: A shortest path from a source vertex to a destination is composed of shortest paths from the source to each of its intermediate vertices.

  2. Maximum Number of Edges in a Shortest Path: In a graph with (V) vertices, a shortest path can contain at most (V-1) edges, provided there is no reachable negative-weight cycle. This is because a shortest path never needs to repeat a vertex.

Implementation

Since each pass guarantees the discovery of shortest paths containing at most one additional edge, after (V-1) passes, it's guaranteed to have discovered the shortest distances from the source to every reachable vertex.

Language
1// Shortest distance from source to every vertex
2public int[] bellmanFord(int V, int[][] edges, int source) {
3
4 // Every vertex starts at infinite distance
5 int[] dist = new int[V];
6 Arrays.fill(dist, Integer.MAX_VALUE);
7
8 // Distance from source to itself is 0
9 dist[source] = 0;
10
11 // A shortest path has at most V - 1 edges,
12 // so relax every edge V - 1 times
13 for (int i = 1; i < V; i++) {
14
15 // Relax each directed edge (u, v, weight)
16 for (int[] edge : edges) {
17
18 int u = edge[0];
19 int v = edge[1];
20 int weight = edge[2];
21
22 // Skip u if it has not been reached yet,
23 // else check if going via u is shorter
24 if (dist[u] != Integer.MAX_VALUE &&
25 dist[u] + weight < dist[v]) {
26
27 // Shorter path to v found through u
28 dist[v] = dist[u] + weight;
29 }
30 }
31 }
32
33 // Each entry is now the shortest distance
34 return dist;
35}
0.7 km0.8 km0.4 km0.4 km0.4 km0.5 km2.1 km2.7 km1.1 km1.1 km0.6 km0.6 km2.4 km1.3 km0.8 km1.0 km2.1 km1.5 km1.8 km2.2 km1.4 km1.5 km0.9 km1.7 km2.4 km2.7 km2.2 km1.4 km1.2 km0.8 km1.4 km1.1 km1.6 km0.6 km1.2 km1.3 km1.7 km2.2 km1.1 km2.0 km1.6 km1.5 km0.5 km0.4 km0.5 km1.9 km1.2 kmKarol BaghPatel NagarJhandewalanSadar BazarKashmere GateKamla MarketTalkatoraRashtrapatiBhavanRajendra PlacePaharganjRam NagarNew DelhiRailway StationAjmeri GateChandni ChowkRed FortConnaught PlaceSTART0.0 kmBarakhambaMandi HouseITODelhi GateJantar MantarWindsor PlaceUdyog BhawanNational MuseumJaipur HouseIndia GateBangla SahibKhan MarketPragatiMaidanJama MasjidLodhi GardenNirman BhawanRamlila Maidan
start

Connaught Place is the starting point, so its distance is 0 km.

From
–
To
–
Road length
–
Distance via this road
–
Pass–
Road–
Places reached1 of 33
currentupdated / reacheddonenot yet
2 / 3011

Time Complexity

Space Complexity


Better Approach: Shortest Path Faster Algorithm (SPFA)

Bellman-Ford processes every edge in every pass, even when the edge's starting vertex has not received a better distance. The key observation behind SPFA is to only process the outgoing edges of vertices whose shortest distances have changed.

An improvement in one node's shortest path can lead to improvements in other nodes' shortest distances. Therefore, whenever we discover a shorter path to a node, we need to explore its neighbours again using the updated distance.

Implementation

SPFA uses a queue to keep track of vertices whose distances have improved and whose outgoing edges need to be explored.

Language
1public int[] shortestPath(int V, List<List<int[]>> adj, int source) {
2
3 int[] dist = new int[V];
4 Arrays.fill(dist, Integer.MAX_VALUE);
5
6 // Tracks whether a vertex is already present in the queue
7 boolean[] inQueue = new boolean[V];
8
9 // Tracks the number of edges in the predecessor path
10 int[] pathEdges = new int[V];
11
12 Queue<Integer> queue = new LinkedList<>();
13
14 // Initialize source
15 dist[source] = 0;
16 queue.offer(source);
17 inQueue[source] = true;
18
19 while (!queue.isEmpty()) {
20
21 int u = queue.poll();
22 inQueue[u] = false;
23
24 // Explore outgoing edges of u
25 for (int[] edge : adj.get(u)) {
26
27 int v = edge[0];
28 int weight = edge[1];
29
30 // Relaxation
31 if (dist[u] != Integer.MAX_VALUE &&
32 dist[u] + weight < dist[v]) {
33
34 dist[v] = dist[u] + weight;
35
36 pathEdges[v] = pathEdges[u] + 1;
37
38 // Detect reachable negative-weight cycle
39 if (pathEdges[v] >= V) {
40 throw new IllegalStateException(
41 "Negative-weight cycle detected"
42 );
43 }
44
45 // Add v only if it is not already in the queue
46 if (!inQueue[v]) {
47 queue.offer(v);
48 inQueue[v] = true;
49 }
50 }
51 }
52 }
53
54 return dist;
55}
0.7 km0.8 km0.4 km0.4 km0.4 km0.5 km2.1 km2.7 km1.1 km1.1 km0.6 km0.6 km2.4 km1.3 km0.8 km1.0 km2.1 km1.5 km1.8 km2.2 km1.4 km1.5 km0.9 km1.7 km2.4 km2.7 km2.2 km1.4 km1.2 km0.8 km1.4 km1.1 km1.6 km0.6 km1.2 km1.3 km1.7 km2.2 km1.1 km2.0 km1.6 km1.5 km0.5 km0.4 km0.5 km1.9 km1.2 kmKarol BaghPatel NagarJhandewalanSadar BazarKashmere GateKamla MarketTalkatoraRashtrapatiBhavanRajendra PlacePaharganjRam NagarNew DelhiRailway StationAjmeri GateChandni ChowkRed FortConnaught PlaceSTART0.0 kmBarakhambaMandi HouseITODelhi GateJantar MantarWindsor PlaceUdyog BhawanNational MuseumJaipur HouseIndia GateBangla SahibKhan MarketPragatiMaidanJama MasjidLodhi GardenNirman BhawanRamlila Maidan
start

Connaught Place is the starting point, so its distance is 0 km, and it is the only place waiting.

From
–
To
–
Road length
–
Distance via this road
–
Waiting1 place
Connaught Place
Roads from here5 roads
Places reached1 of 33
3 / 131

Time Complexity

The time complexity depends on the the following operations:

  1. Initializing the adjacency list: We iterate over all vertices to initialize their adjacency lists, which takes O(V) time. We then iterate over all edges to populate the adjacency list. Since the graph is undirected, each edge is added to the adjacency lists of both endpoints. This takes O(E) time. Therefore, this takes O(V + E).

  2. Queue processing: A node can be enqueued and processed multiple times. Whenever we process a node, we explore all its neighbours. In the worst case, every single vertex gets updated and re-queued (V - 1) times. f every vertex is popped O(V) times and each pop checks all its outgoing edges, the sum of all edge checks across all vertices equals O(V * E). ------ Need to explore this more -----

  3. Converting unreachable nodes to -1: We iterate over the answer array once to identify unreachable nodes and update their values to -1. Since the array contains (V) elements, this takes O(V).

Hence, the overall time complexity is O(V + E) + O(V * E) + O(V) = O(V * E).

Space Complexity

The space complexity is primarily determined by three data structures:

  1. Adjacency list: Each of the (V) vertices requires an adjacency list. Each of the (E) edges is stored twice because the graph is undirected. This takes O(V + E).

  2. answer array: Since the array contains (V) elements, this takes O(V).

  3. Queue: In the standard SPFA implementation, we maintain an additional inQueue[] array. Whenever we enqueue a node, we mark it as present in the queue. We only enqueue it again after it has been removed from the queue. This ensures that at any given time, each vertex can appear in the queue at most once. This takes O(V).

Hence, the overall space complexity is O(V + E). ------ Need to explore this more -----


Suitable Approach: Dijkstra's Algorithm

SPFA avoids unnecessary edge processing, but it still has an important limitation. It uses a regular FIFO queue. This means vertices are processed in the order they are added, not according to how close they are to the source. Key observations that make dijkstra work:

  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.

Implementation

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.

Language
1public int[] shortestPath(int V, List<List<int[]>> adj, int source) {
2
3 int[] dist = new int[V];
4 Arrays.fill(dist, Integer.MAX_VALUE);
5
6 // Min-priority queue: {distance, vertex}
7 PriorityQueue<int[]> pq = new PriorityQueue<>(
8 (a, b) -> Integer.compare(a[0], b[0])
9 );
10
11 // Initialize source
12 dist[source] = 0;
13 pq.offer(new int[]{0, source});
14
15 while (!pq.isEmpty()) {
16
17 int[] current = pq.poll();
18
19 int currentDist = current[0];
20 int u = current[1];
21
22 // Ignore stale entries
23 if (currentDist > dist[u]) {
24 continue;
25 }
26
27 // Explore outgoing edges
28 for (int[] edge : adj.get(u)) {
29
30 int v = edge[0];
31 int weight = edge[1];
32
33 // Edge relaxation
34 if (currentDist + weight < dist[v]) {
35
36 dist[v] = currentDist + weight;
37
38 pq.offer(new int[]{dist[v], v});
39 }
40 }
41 }
42
43 return dist;
44}
0.7 km0.8 km0.4 km0.4 km0.4 km0.5 km2.1 km2.7 km1.1 km1.1 km0.6 km0.6 km2.4 km1.3 km0.8 km1.0 km2.1 km1.5 km1.8 km2.2 km1.4 km1.5 km0.9 km1.7 km2.4 km2.7 km2.2 km1.4 km1.2 km0.8 km1.4 km1.1 km1.6 km0.6 km1.2 km1.3 km1.7 km2.2 km1.1 km2.0 km1.6 km1.5 km0.5 km0.4 km0.5 km1.9 km1.2 kmKarol BaghPatel NagarJhandewalanSadar BazarKashmere GateKamla MarketTalkatoraRashtrapatiBhavanRajendra PlacePaharganjRam NagarNew DelhiRailway StationAjmeri GateChandni ChowkRed FortConnaught PlaceSTART0.0 kmBarakhambaMandi HouseITODelhi GateJantar MantarWindsor PlaceUdyog BhawanNational MuseumJaipur HouseIndia GateBangla SahibKhan MarketPragatiMaidanJama MasjidLodhi GardenNirman BhawanRamlila Maidan
start

Connaught Place is the starting point, so its distance is 0 km, and it is the closest place waiting.

From
–
To
–
Road length
–
Distance via this road
–
Queue1 entry
Connaught Place · 0.0 km
Roads from here5 roads
Places reached1 of 33
3 / 134

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).