Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Dijkstra's Algorithm: Finding Shortest Paths

This lesson is built with resources from youtube.com, happycoders.eu and 1 more site.

Introduction

In our last lesson, we saw how Breadth-First Search (BFS) is the perfect tool for finding the shortest path in an unweighted graph, where every step has a uniform cost. We applied this to the "Word Ladder" problem, treating it as a state-space search.

Now, let's evolve this concept. What happens when the path is not just about the number of steps, but the "cost" of those steps? Imagine a GPS navigating a city: some roads are fast highways, others are slow local streets. This is a shortest path problem on a weighted graph.

Today, you will learn to solve such problems using Dijkstra's algorithm. This is one of the most fundamental and widely used graph algorithms, especially for finding the single-source shortest path in graphs with non-negative edge weights. Understanding Dijkstra's is essential, not only for interviews but also for its vast applications in networking, logistics, and, as you might guess, navigation systems for companies like Google and Uber.


From Roads to Graphs: The Core Idea

At its heart, Dijkstra's algorithm solves a very practical problem. How do you find the fastest route from your current location to all other possible destinations?

From A to B: Algorithms That Power Google Maps Navigation

To frame our thinking, let's start with this article that connects abstract graph theory to a concrete application: Google Maps. It provides excellent context for why we need algorithms like Dijkstra's.

Read the sections 'Roads as Graphs: The Core Idea' and 'Dijkstra’s Algorithm: The Foundation'. This will set the stage by modeling road networks as weighted graphs.

As the article highlights, we can model a map as a graph where:

  • Nodes (Vertices) are intersections or locations.
  • Edges are the roads connecting them.
  • Weights are the costs associated with traversing those roads (e.g., travel time, distance).

Dijkstra's algorithm provides a systematic way to find the path with the minimum total weight from a single starting node to every other node.


How Dijkstra's Algorithm Works

Dijkstra's algorithm is a greedy algorithm. It works by maintaining a set of visited nodes and, at each step, greedily selecting the unvisited node that is closest to the source.

The core logic relies on a few key data structures:

  1. Distances Map/Array: Stores the shortest distance found so far from the source to every other node. We initialize the source's distance to 0 and all others to infinity.
  2. Min-Priority Queue: This is the engine of the algorithm. It stores nodes to be visited, prioritized by their current shortest distance. This ensures we always explore from the "closest" unvisited node first.
  3. Visited Set: Tracks nodes for which we have finalized their shortest distance, preventing redundant processing.

The Crucial Constraint: Non-Negative Weights

The greedy strategy of "finalizing" the shortest path to the closest node only works if edge weights are non-negative. If a negative edge existed, a path that currently looks longer could suddenly become shorter later on, invalidating our greedy choice. We'll address graphs with negative weights in the next lesson.

Let's watch a video that explains the algorithm's mechanics and provides a detailed walkthrough.

Dijkstra’s Algorithm for Coding Interviews | Single Source Shortest Path (Greedy Algorithm)

This video by Shiran Afergan offers a clear explanation of the algorithm's greedy nature, the data structures involved, and a step-by-step visual walkthrough. It's a great way to build a solid mental model.

Please watch the following segments: 00:00 - 01:43: Introduction and the non-negative weight constraint. 01:43 - 03:32: The algorithm's logic, explaining the role of the min-heap and the 'relaxation' step. 04:15 - 09:25: A detailed example walkthrough. Follow how the distances, predecessors, and min-heap are updated at each step.

To reinforce the process, here is a static visualization of the algorithm's execution on a sample graph.

Step-by-Step Dijkstra's Algorithm Visualization
This diagram shows the four main steps of Dijkstra's algorithm starting from vertex v1. At each step, the algorithm selects the unvisited vertex with the smallest known distance (highlighted in blue), relaxes its outgoing edges, and updates the distances to its neighbors if a shorter path is found. The final path from v1 to v2 is determined by backtracking through the predecessors.

Why a Priority Queue? The Difference from BFS

A key point that elevates this from a simple traversal to an efficient shortest-path algorithm is the use of a min-priority queue instead of a regular queue (as in BFS).

With a regular queue, you explore nodes in the order they were discovered. With a priority queue, you explore nodes in the order of their distance from the source. This greedy choice is what makes Dijkstra's work for weighted graphs.

G-34. Dijkstra's Algorithm - Why PQ and not Q, Intuition, Time Complexity Derivation - Part 3

Let's explore the intuition behind this critical design choice. This video from 'take U forward' excellently demonstrates why a standard queue is inefficient and leads to unnecessary work, solidifying why the priority queue is essential.

Watch from 00:48 to 06:43. The narrator walks through the same graph using a regular queue, highlighting the extra, suboptimal paths that get explored. This clearly illustrates the efficiency gain from the greedy approach of a priority queue.


Go Implementation with container/heap

Now, let's translate this into idiomatic Go. Go's standard library doesn't provide a ready-made priority queue, but it offers the container/heap package, which provides the necessary heap operations. We can build our own priority queue by implementing the heap.Interface.

Here's a breakdown of the implementation:

  1. Define an Item struct: This will hold the node, its priority (distance), and its index in the heap (needed for updates).
  2. Define the PriorityQueue type: A slice of *Item pointers.
  3. Implement heap.Interface: This involves creating five methods for our PriorityQueue type: Len, Less, Swap, Push, and Pop. The Less method is key, as it defines the min-priority logic (p.items[i].priority < p.items[j].priority).
  4. Write the Dijkstra function: This function will use our newly created priority queue to execute the algorithm's main loop.

Here is a full Go implementation. Study how the pieces fit together.

package main

import (
	"container/heap"
	"fmt"
	"math"
)

// Item represents an item in our priority queue.
type Item struct {
	node     string // The node's name/value
	priority int    // The distance from the source
	index    int    // The item's index in the heap.
}

// PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the smallest priority, so we use less than here.
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

// Push adds an item to the priority queue.
func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

// Pop removes and returns the minimum element (by priority) from the priority queue.
func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// Dijkstra finds the shortest paths from a source node to all other nodes.
func Dijkstra(graph map[string]map[string]int, source string) (map[string]int, map[string]string) {
	// 1. Initialize distances, predecessors, and the priority queue.
	distances := make(map[string]int)
	predecessors := make(map[string]string)
	pq := make(PriorityQueue, 0)
    
    // A map to help find items in the priority queue quickly
	itemMap := make(map[string]*Item)

	for node := range graph {
		distances[node] = math.MaxInt32
		predecessors[node] = ""
	}
	distances[source] = 0

	// Create the source item and push it to the queue.
	sourceItem := &Item{node: source, priority: 0}
	heap.Push(&pq, sourceItem)
	itemMap[source] = sourceItem

	// 2. Main loop
	for pq.Len() > 0 {
		// Get the node with the smallest distance
		currentItem := heap.Pop(&pq).(*Item)
		u := currentItem.node

		// 3. Relaxation step for each neighbor
		for v, weight := range graph[u] {
			// If a shorter path to v is found through u
			if distances[u]+weight < distances[v] {
				distances[v] = distances[u] + weight
				predecessors[v] = u
                
                // If neighbor is already in the queue, update its priority.
                // Otherwise, add it.
				if neighborItem, found := itemMap[v]; found {
                    neighborItem.priority = distances[v]
                    heap.Fix(&pq, neighborItem.index)
				} else {
					newItem := &Item{node: v, priority: distances[v]}
					heap.Push(&pq, newItem)
					itemMap[v] = newItem
				}
			}
		}
	}

	return distances, predecessors
}

Note: The implementation above shows updating an item in the heap using heap.Fix. A simpler, common interview approach is to just push the new, shorter path (distance, node) pair to the heap, and add a check to ignore nodes popped from the heap if we've already found a shorter path to them (i.e., if popped_distance > distances[node]). Both are valid; the heap.Fix approach is slightly more memory-efficient.


Staff-Level Topic: Complexity and Data Structure Trade-offs

For a Staff-level interview, simply implementing the algorithm is not enough. You must be able to analyze its performance deeply and discuss the trade-offs of different implementation choices.

Time and Space Complexity

The complexity depends heavily on the data structures used, particularly the priority queue.

  • Time Complexity:

    • We extract each vertex from the min-priority queue once. Each extraction costs . Total: .
    • We iterate through all edges once. For each edge, we might perform a "decrease-key" operation on the priority queue if a shorter path is found. In a binary heap, this is also . Total: .
    • Combining these gives , which is commonly written as since in connected graphs, .
  • Space Complexity:

    • for the graph's adjacency list representation.
    • for the distances and predecessors maps.
    • for the priority queue, which holds at most one entry per vertex.

For a rigorous mathematical derivation of the time complexity, the take U forward video provides an excellent deep dive.

G-34. Dijkstra's Algorithm - Why PQ and not Q, Intuition, Time Complexity Derivation - Part 3

To really solidify your understanding of the performance, let's watch a detailed derivation of the time complexity.

Watch from 06:43 to 13:47. This section breaks down the complexity analysis step-by-step, explaining how the operations on the priority queue contribute to the final O(E log V) complexity.

Data Structure Trade-offs

While a binary heap (like Go's container/heap) is standard, other data structures can be used for the priority queue, leading to different performance characteristics. Discussing this shows a sophisticated understanding of algorithms and data structures.

Dijkstra's Algorithm - Time Complexity Summary

This article from HappyCoders.eu provides an outstanding analysis of Dijkstra's runtime with different underlying data structures. The summary table is particularly valuable.

Scroll to the 'Time Complexity – Summary' section and study the table. You don't need to implement a Fibonacci Heap, but you should understand its theoretical advantage (amortized O(1) decrease-key) and how that changes the overall complexity to O(E + V log V).

In an interview, you could mention: "My implementation uses a standard binary heap, giving time. If performance were absolutely critical and we were dealing with very dense graphs, we could consider a Fibonacci heap, which offers a better theoretical complexity of due to its amortized constant time for the decrease-key operation, though it has higher practical overhead."


Conclusion

In this lesson, we moved from unweighted to weighted graphs, uncovering the need for a more sophisticated shortest-path algorithm. We learned that Dijkstra's algorithm provides an efficient, greedy solution for the single-source shortest path problem, provided all edge weights are non-negative.

Key Takeaways:

  • Dijkstra's algorithm finds the shortest path from a single source to all other nodes in a weighted graph with non-negative weights.
  • Its greedy strategy is to always explore the unvisited node with the smallest known distance from the source.
  • The efficiency of the algorithm hinges on using a min-priority queue to quickly select the next node to visit, resulting in a time complexity of .
  • For Staff-level discussions, be prepared to analyze complexity rigorously and discuss the trade-offs of using different underlying data structures for the priority queue (e.g., binary heap vs. Fibonacci heap).

In our next lesson, we will tackle the limitation of Dijkstra's algorithm by asking: what if the graph does have negative edge weights? This will lead us to the Bellman-Ford algorithm, a more robust but slower alternative.