Back to DSA Guide Catalog

Algorithmextra-hard

Dijkstra Shortest Path Complete Guide

Dijkstra computes shortest paths from one source in graphs with non-negative edge weights.

It repeatedly picks the currently cheapest frontier node using a min-priority queue.

When weights can be negative, use Bellman-Ford or other alternatives instead.

Typical Complexity Baseline

MetricValue
Complexity Note 1O((V + E) log V) with heap

Video Explainer

Prefer video learning? This explainer gives a quick visual walkthrough of the core idea before you dive into the detailed sections below.

Dijkstra Visualizer

Track how the min-priority frontier relaxes weighted paths from the source.

Dijkstra VisualizerStep 1 / 4

Initialize source distance to zero and others to infinity.

Source

A

Distances

A:0, B:∞, C:∞, D:∞, E:∞

Priority Queue

[(0,A)]

Settled Nodes

{}

Core Concepts

Learn the core building blocks and terminology in one place before comparisons, so the mechanics are clear and duplicates are removed.

Distance array

What it is: Best-known distance from source to each node.

Why it matters: Distance array is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Priority queue

What it is: Frontier by smallest current distance.

Why it matters: Priority queue is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Relaxation

What it is: Try improving neighbor distance via current node. Update distance if new path is cheaper.

Why it matters: Relaxation is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs. Update distance if new path is cheaper. In Dijkstra Shortest Path, this definition helps you reason about correctness and complexity when inputs scale.

Visited/finalized set

What it is: Optional optimization to skip stale states.

Why it matters: Visited/finalized set is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Adjacency list

What it is: Outgoing weighted edges per node.

Why it matters: Adjacency list is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Stale heap entry

What it is: Queue entry whose distance no longer matches best known value.

Why it matters: Queue entry whose distance no longer matches best known value. In Dijkstra Shortest Path, this definition helps you reason about correctness and complexity when inputs scale.

Non-negative weight

What it is: Edge cost >= 0 required for Dijkstra correctness.

Why it matters: Edge cost >= 0 required for Dijkstra correctness. In Dijkstra Shortest Path, this definition helps you reason about correctness and complexity when inputs scale.

Single-source shortest path

What it is: Shortest paths from one source to all nodes.

Why it matters: Shortest paths from one source to all nodes. In Dijkstra Shortest Path, this definition helps you reason about correctness and complexity when inputs scale.

Shortest path tree

What it is: Parent pointers describing chosen shortest paths.

Why it matters: Parent pointers describing chosen shortest paths. In Dijkstra Shortest Path, this definition helps you reason about correctness and complexity when inputs scale.

Putting It All Together

This walkthrough connects the core concepts of Dijkstra Shortest Path into one end-to-end execution flow.

Step 1

Distance array

Best-known distance from source to each node.

Before

dist

source
  • =0, others=∞
  • Priority queue=[(0, source)]

After

  • Current node finalized candidate
  • Ready to relax neighbors

Transition

Pop smallest distance node
Treat it as next frontier

Why this step matters: Distance array is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Step 2

Priority queue

Frontier by smallest current distance.

Before

  • Current node u with dist=3
  • Neighbor v via edge weight 4

After

dist

v
  • improved
  • Push (7, v) to queue

Transition

candidate = 3 + 4 = 7
If candidate < dist[v], update dist[v]

Why this step matters: Priority queue is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Step 3

Relaxation

Try improving neighbor distance via current node.

Before

  • Queue may contain stale entries
  • Popped entry distance might be outdated

After

  • Only best-known states expanded
  • Performance and correctness preserved

Transition

Compare popped distance to dist[node]
Skip if mismatch

Why this step matters: Relaxation is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

Step 4

Visited/finalized set

Optional optimization to skip stale states.

Before

  • Queue eventually empties
  • All reachable nodes processed

After

  • Shortest distances finalized
  • Unreachable nodes remain ∞

Transition

Read dist[] table
Optional parent[] for path reconstruction

Why this step matters: Visited/finalized set is a required building block for understanding how Dijkstra Shortest Path stays correct and performant on large inputs.

How It Compares

vs BFS

When to choose this: Choose Dijkstra when edge weights differ.

Tradeoff: BFS is faster/simpler for unweighted graphs.

vs Bellman-Ford

When to choose this: Choose Dijkstra for non-negative weights and better performance.

Tradeoff: Bellman-Ford supports negative edges at higher cost.

vs A*

When to choose this: Choose Dijkstra when no admissible heuristic is available.

Tradeoff: A* can be faster toward single target with good heuristic.

Real-World Stories and Company Examples

Google Maps

Route planning systems rely on shortest-path families including Dijkstra-style expansion phases.

Takeaway: Weighted graph pathing is core in location products.

Network routers

Link-state routing protocols historically use Dijkstra-like SPF computations.

Takeaway: Internet infrastructure uses shortest-path algorithms in control planes.

Ride-hailing platforms

ETA and routing services evaluate weighted travel graphs continuously.

Takeaway: Path-cost optimization directly affects product quality.

Implementation Guide

Use min-priority frontier and relax edges from cheapest-known node each step.

Complexity: O((V+E) log V) with binary heap

Dijkstra shortest distances

type WeightedEdge = { edgeWeight: number; neighborNode: number }

type HeapNode = { distance: number; node: number }

class MinDistanceHeap {
  private readonly values: HeapNode[] = []

  push(params: HeapNode): void {
    this.values.push(params)
    this.bubbleUp(this.values.length - 1)
  }

  pop(): HeapNode | null {
    if (this.values.length === 0) return null
    const rootValue = this.values[0]
    const lastValue = this.values.pop()
    if (this.values.length > 0 && lastValue) {
      this.values[0] = lastValue
      this.bubbleDown(0)
    }
    return rootValue
  }

  private bubbleUp(startIndex: number): void {
    let currentIndex = startIndex
    while (currentIndex > 0) {
      const parentIndex = Math.floor((currentIndex - 1) / 2)
      if (this.values[parentIndex].distance <= this.values[currentIndex].distance) break
      ;[this.values[parentIndex], this.values[currentIndex]] = [this.values[currentIndex], this.values[parentIndex]]
      currentIndex = parentIndex
    }
  }

  private bubbleDown(startIndex: number): void {
    let currentIndex = startIndex
    while (true) {
      const leftChildIndex = currentIndex * 2 + 1
      const rightChildIndex = currentIndex * 2 + 2
      let smallestIndex = currentIndex

      if (leftChildIndex < this.values.length && this.values[leftChildIndex].distance < this.values[smallestIndex].distance) {
        smallestIndex = leftChildIndex
      }
      if (rightChildIndex < this.values.length && this.values[rightChildIndex].distance < this.values[smallestIndex].distance) {
        smallestIndex = rightChildIndex
      }
      if (smallestIndex === currentIndex) break

      ;[this.values[currentIndex], this.values[smallestIndex]] = [this.values[smallestIndex], this.values[currentIndex]]
      currentIndex = smallestIndex
    }
  }
}

function dijkstraShortestDistances(params: { adjacencyByNode: WeightedEdge[][]; sourceNode: number }): number[] {
  const distanceByNode = new Array<number>(params.adjacencyByNode.length).fill(Number.POSITIVE_INFINITY)
  distanceByNode[params.sourceNode] = 0

  const frontierHeap = new MinDistanceHeap()
  frontierHeap.push({ distance: 0, node: params.sourceNode })

  while (true) {
    const nextEntry = frontierHeap.pop()
    if (!nextEntry) break

    if (nextEntry.distance !== distanceByNode[nextEntry.node]) {
      continue
    }

    for (const edge of params.adjacencyByNode[nextEntry.node]) {
      const candidateDistance = nextEntry.distance + edge.edgeWeight
      if (candidateDistance < distanceByNode[edge.neighborNode]) {
        distanceByNode[edge.neighborNode] = candidateDistance
        frontierHeap.push({ distance: candidateDistance, node: edge.neighborNode })
      }
    }
  }

  return distanceByNode
}

Common Problems and Failure Modes

  • Using Dijkstra on graphs with negative edges.
  • Not skipping stale priority queue entries.
  • Incorrect relaxation condition.
  • Initializing distances incorrectly.
  • Assuming path reconstruction without storing parent pointers.

Tips and Tricks

  • Dijkstra requires non-negative edge weights; verify this before coding.
  • Use min-heap and skip stale entries to keep complexity under control.
  • Store parent pointers when path reconstruction is required, not only distances.
  • For unweighted graphs, BFS is simpler and often faster.

When to Use

Use these signals to decide if this data structure/algorithm is the right fit before implementation.

Real-system usage signals

  • Reliable shortest-path results for weighted non-negative graphs.
  • Efficient with adjacency list + heap for sparse graphs.
  • Applicable to routing, scheduling, and cost optimization problems.

LeetCode-specific tips (including pattern-identification signals)

  • Identification signal: shortest path on weighted graph with non-negative edge weights.
  • Identification signal: you repeatedly expand the currently cheapest-known frontier node.
  • If edges have weights and BFS no longer works correctly, Dijkstra is often the next step.
  • For Dijkstra Shortest Path questions, start by naming the core invariant before writing code.
  • Use the constraint section to set time/space target first, then pick the data structure/algorithm.
  • Solve one tiny example by hand and map each transition to your variables before implementing.
  • Run adversarial cases: empty input, duplicates, max-size input, and sorted/reverse patterns when relevant.
  • During interviews, explain why your approach is the right pattern for this prompt, not just why the code works.

LeetCode Progression (Easy to Hard)

Back to DSA Guide Catalog
#ProblemDifficultyTypical Complexity
1Network Delay TimeMediumO((V+E) log V)
2Path With Minimum EffortMediumO((V+E) log V)
3Cheapest Flights Within K StopsMediumVaries
4Number of Ways to Arrive at DestinationMediumO((V+E) log V)
5The Maze IIMediumO((V+E) log V)
6Swim in Rising WaterHardO(n^2 log n)
7Minimum Cost to Reach Destination in TimeHardO((V+E) log V)
8Reachable Nodes In Subdivided GraphHardO((V+E) log V)
9Minimum Weighted Subgraph With the Required PathsHardO((V+E) log V)
10Second Minimum Time to Reach DestinationHardGraph shortest-path variant