Skip to main content

LeetCode Patterns

Dijkstra's Shortest Path Pattern

Dijkstra's algorithm computes the shortest path from a single source to every other vertex in a weighted graph with non-negative edge weights. It is the canonical answer to shortest-path interview questions — using a min-heap to always extract the next-closest unvisited vertex — and runs in O((V + E) log V) with a binary heap, which is fast enough for nearly every grid, graph, or network problem you will see.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Complexity

Time
O((V + E) log V) with a binary heap
Space
O(V + E)

When to use Dijkstra's Shortest Path

  • The graph has weighted edges and all weights are non-negative.
  • You need the shortest path (or the shortest-path distance) from a single source to one or all other nodes.
  • Plain BFS would give wrong answers because edge weights are not all equal.
  • The problem can be modeled as a graph where states are nodes and transitions carry a cost — including grid problems where moves have different costs.
  • You need the minimum total cost (time, distance, effort) to reach a target, not just whether the target is reachable.

Template

function dijkstra(numNodes, edges, source) {
  const graph = Array.from({ length: numNodes }, () => []);
  for (const [from, to, weight] of edges) {
    graph[from].push([to, weight]);
  }
  const dist = new Array(numNodes).fill(Infinity);
  dist[source] = 0;
  const heap = [[0, source]];
  while (heap.length > 0) {
    heap.sort((a, b) => a[0] - b[0]);
    const [d, node] = heap.shift();
    if (d > dist[node]) continue;
    for (const [next, weight] of graph[node]) {
      const nd = d + weight;
      if (nd < dist[next]) {
        dist[next] = nd;
        heap.push([nd, next]);
      }
    }
  }
  return dist;
}

Example LeetCode problems

#ProblemDifficultyFrequency
743Network Delay Timemediumfoundational
787Cheapest Flights Within K Stopsmediumcompany favorite
1631Path With Minimum Effortmediumfrequently asked
778Swim in Rising Waterhardclassic
1514Path with Maximum Probabilitymediumfrequently asked
505The Maze IImediumfrequently asked
1368Minimum Cost to Make at Least One Valid Path in a Gridhardcompany favorite
3553Shortest Path in a Weighted Treehardless common

Common mistakes

  • Running Dijkstra on a graph with negative edge weights — it silently returns wrong answers because the greedy 'closest unvisited' invariant breaks the moment a future edge can decrease an already-settled distance.
  • Forgetting the stale-entry skip (`if (d > dist[node]) continue;`) and re-relaxing neighbors of an outdated heap entry, which inflates the runtime to O(V^2 log V) on dense graphs.
  • Marking a node as visited the moment it is pushed onto the heap instead of when it is popped, which prevents legitimate shorter paths from being processed.
  • Initializing the distance array with 0 or undefined instead of Infinity, so the first relaxation never fires for unreachable nodes.
  • Using a regular FIFO queue instead of a min-heap — this is BFS, not Dijkstra, and works only when all edge weights are equal.

Frequently asked questions

Why does Dijkstra fail with negative edge weights?

Dijkstra commits to the shortest known distance to a node the moment it pops that node from the heap, relying on the invariant that no future path can be shorter. A negative edge can later create a shorter path to an already-popped node, breaking the invariant. Use Bellman-Ford or SPFA for graphs that may contain negative edges.

When should I use BFS instead of Dijkstra?

Use BFS when all edges have the same weight — typically weight 1 — because BFS already finds shortest paths in O(V + E) without the log factor for the heap. Dijkstra collapses to BFS in this case anyway, but the heap overhead is wasted work.

What is the difference between Dijkstra and A*?

A* augments Dijkstra with a heuristic h(n) that estimates the remaining cost from n to the target. The priority becomes dist[n] + h(n) instead of just dist[n], which steers the search toward the goal and avoids exploring directions that lead away from it. With an admissible heuristic, A* returns the same optimal path as Dijkstra, usually faster.

How do I reconstruct the actual shortest path, not just the distance?

Maintain a parent[] array alongside dist[]. Every time you relax an edge (u, v) and update dist[v], set parent[v] = u. After the algorithm finishes, walk backward from the target through parent[] to the source, then reverse the result. This adds O(V) memory and constant work per relaxation.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill the Dijkstra's Shortest Path pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →