Dijkstra's algorithm explained

Dijkstra's algorithm finds the shortest distance from one start node to every other node in a graph whose edge weights are zero or positive. It always expands the closest node not yet finished, which a min-heap hands back in O(log n), so the whole run costs O((V + E) log V). It is the default answer whenever an interview problem asks for the cheapest, fastest or shortest route and no weight can be negative.

By Published 10 min read

The task, restated

A courier company has n depots numbered 0 to n - 1 and a list of one-way routes. Each route is a triple (from, to, minutes) and the minutes are never negative. At time 0 a parcel is ready at depot src, and the moment any depot holds a copy, it sends copies down all of its outgoing routes. You must return the time at which the last depot receives its first copy, or -1 if some depot can never be reached. Under the story, that is the largest shortest-path distance from src, which is exactly what Dijkstra computes.

Examples made up for this page (src is depot 0 in every row)
nRoutes (from, to, minutes)AnswerWhy
5(0,1,4) (0,2,1) (2,1,2) (1,3,1) (2,3,5) (3,4,3)7Shortest times are 0, 3, 1, 4, 7; depot 1 is faster through depot 2
3(0,1,5)-1Nothing ever reaches depot 2
3(0,1,0) (1,2,0)0Zero-minute routes are allowed
2(0,1,9) (0,1,2)2Two parallel routes; the cheaper one counts
1none0The start depot already has the parcel
Examples made up for this page (src is depot 0 in every row). Scroll sideways on a small screen.

Clarify a few points before you start. Are the routes one-way, as here, or two-way? Can minutes be zero or negative? Is n small enough that a dense O(n²) version is fine, or large and sparse? And do they want only the time, or also the route that achieves it? The negative-weight question matters most, because it decides whether Dijkstra is allowed at all.

Why this comes up so often

Shortest paths are one of the few graph topics that interviewers expect almost everyone to know, and Dijkstra is where the heap, the graph representation and a greedy proof meet in one short function. The usual signals that the problem wants it: weighted edges, a single start point, and a question about the minimum total cost. Some variants worth recognizing:

  • Grid with a cost per cell. Each cell is a node, its four neighbors are edges, and the weight is the cost of stepping in.
  • Cheapest route with at most k stops. Plain Dijkstra can discard a pricier path that uses fewer stops; track (cost, stops) as the state or run k + 1 rounds of Bellman-Ford.
  • Path with the highest success probability. Multiply probabilities and pop the largest first, using a max-heap, or turn them into weights with a negative logarithm.
  • Minimize the largest single step on the route. Replace the sum with a max when you relax an edge; the same pop order still works.
  • All edges weigh 1. Plain BFS gives the same answer in O(V + E) without a heap. If the weights are only 0 and 1, a deque-based BFS does too.

A slower start: Bellman-Ford

Bellman-Ford sets every distance to infinity except the start, then sweeps all routes again and again. In each sweep, any route that offers a shorter time to its end depot updates it. After V - 1 sweeps no shortest path can still be missing, because a shortest path never needs more than V - 1 edges. That is O(V times E), which is slow for large graphs, but it is short and handles negative weights, so it doubles as an excellent reference for testing.

import math

def shortest_times_slow(n, routes, src):
    dist = [math.inf] * n
    dist[src] = 0
    for _ in range(n - 1):
        changed = False
        for a, b, minutes in routes:
            if dist[a] + minutes < dist[b]:
                dist[b] = dist[a] + minutes
                changed = True
        if not changed:
            break
    return dist
Bellman-Ford baseline. It stops early once a sweep changes nothing.

The idea behind Dijkstra

Imagine the parcel spreading in real time. The first depot to receive it, after the start, must be the one at the end of the cheapest route out of src, because every other way of getting anywhere takes at least that long. The same reasoning repeats: among depots not yet reached, the next to receive the parcel is the one with the smallest known arrival time, and no later discovery can beat it. That only works because minutes are never negative. A detour cannot get cheaper by adding more routes.

A min-heap holds candidate (time, depot) pairs. Pop the smallest; if its time is worse than the best already recorded for that depot, it is a stale copy and you skip it. Otherwise, relax each outgoing route: if going through this depot is faster than the best known time at the other end, record the new time and push it. Leaving stale entries in the heap and skipping them on pop is called lazy deletion, and it is how most people write Dijkstra with a library heap that has no decrease-key operation.

Optimal approach: min-heap with lazy deletion

import heapq
import math

def shortest_times(n, routes, src):
    out = [[] for _ in range(n)]
    for a, b, minutes in routes:
        out[a].append((b, minutes))
    dist = [math.inf] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        t, depot = heapq.heappop(heap)
        if t > dist[depot]:
            continue  # stale entry, a faster time was already recorded
        for nxt, minutes in out[depot]:
            arrive = t + minutes
            if arrive < dist[nxt]:
                dist[nxt] = arrive
                heapq.heappush(heap, (arrive, nxt))
    return dist

def last_arrival(n, routes, src):
    worst = max(shortest_times(n, routes, src))
    return -1 if worst == math.inf else worst
Python: heapq orders tuples by time first.
class MinHeap {
  constructor() {
    this.items = [];
  }
  get size() {
    return this.items.length;
  }
  push(entry) {
    const a = this.items;
    a.push(entry);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (a[p][0] <= a[i][0]) break;
      [a[p], a[i]] = [a[i], a[p]];
      i = p;
    }
  }
  pop() {
    const a = this.items;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let m = i;
        if (l < a.length && a[l][0] < a[m][0]) m = l;
        if (r < a.length && a[r][0] < a[m][0]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]];
        i = m;
      }
    }
    return top;
  }
}

function shortestTimes(n, routes, src) {
  const out = Array.from({ length: n }, () => []);
  for (const [a, b, minutes] of routes) out[a].push([b, minutes]);
  const dist = new Array(n).fill(Infinity);
  dist[src] = 0;
  const heap = new MinHeap();
  heap.push([0, src]);
  while (heap.size > 0) {
    const [t, depot] = heap.pop();
    if (t > dist[depot]) continue;
    for (const [nxt, minutes] of out[depot]) {
      const arrive = t + minutes;
      if (arrive < dist[nxt]) {
        dist[nxt] = arrive;
        heap.push([arrive, nxt]);
      }
    }
  }
  return dist;
}

function lastArrival(n, routes, src) {
  const worst = Math.max(...shortestTimes(n, routes, src));
  return worst === Infinity ? -1 : worst;
}
JavaScript has no built-in heap, so a small binary heap comes first.

In an interview, say out loud that you would use a library priority queue in production and that you are writing the heap only because the language lacks one. Many interviewers will let you assume a heap exists in JavaScript; ask before spending ten minutes on it. For very large graphs, Math.max with the spread operator can hit argument limits, so a simple loop is safer there.

Trace on the first example

Routes (0,1,4) (0,2,1) (2,1,2) (1,3,1) (2,3,5) (3,4,3), start 0
PopResultUpdatesdist after
(0, 0)fresh1 gets 4, 2 gets 1[0, 4, 1, inf, inf]
(1, 2)fresh1 improves to 3, 3 gets 6[0, 3, 1, 6, inf]
(3, 1)fresh3 improves to 4[0, 3, 1, 4, inf]
(4, 1)stale, 4 > 3noneunchanged
(4, 3)fresh4 gets 7[0, 3, 1, 4, 7]
(6, 3)stale, 6 > 4noneunchanged
(7, 4)freshno outgoing routes[0, 3, 1, 4, 7]
Routes (0,1,4) (0,2,1) (2,1,2) (1,3,1) (2,3,5) (3,4,3), start 0. Scroll sideways on a small screen.

The largest value is 7, so the last depot gets the parcel at minute 7. Two stale pops appear even in this tiny graph, which is why the skip check is not optional. Without it, the code still returns the right distances here, but it relaxes edges from outdated times and does needless work on larger inputs.

Follow-up: return the route itself

Keep a prev array next to dist. Each time a route improves dist[nxt], set prev[nxt] to the depot you came from. To rebuild the path to a target, follow prev back from the target to src and reverse the list. If dist[target] is still infinity, there is no route. The extra cost is O(V) space and O(length of the path) time to rebuild.

Why negative weights break it

Take routes (0,1,2), (0,2,3) and (2,1,-2). The textbook version that marks a depot finished when it is popped finishes depot 1 at time 2, then later finds the path through depot 2 that costs 1, too late. The lazy version above happens to recover in small cases because it pushes the improvement again, but it loses its time bound and can do a huge amount of work on bad inputs. If weights can be negative, use Bellman-Ford, which also detects negative cycles with one extra sweep.

Time and space

V depots, E routes
ApproachTimeSpaceUse when
Bellman-FordO(V times E)O(V)Weights may be negative
Dijkstra, array scan for the minimumO(V²)O(V)Dense graphs where E is close to V²
Dijkstra, binary heap with lazy deletionO((V + E) log V)O(V + E)The usual interview answer
BFSO(V + E)O(V)Every edge has the same weight
V depots, E routes. Scroll sideways on a small screen.

Edge cases

  • A single depot: the answer is 0, since the start already holds the parcel.
  • Unreachable depots: their distance stays infinity, so the answer is -1. Check for this before taking the max, or test the max against infinity as above.
  • Zero-minute routes are fine. Dijkstra only needs weights that are not negative.
  • Parallel routes between the same pair: the cheaper one wins automatically through the relax check.
  • Self-loops: relaxing a depot to itself never improves it, so they are harmless.
  • Ids numbered 1 to n: allocate n + 1 slots or subtract one when reading routes, and say which you chose.

Mistakes to avoid

  • Using a plain queue instead of a min-heap. That is BFS, and it gives wrong answers once weights differ.
  • Marking a depot visited when it is pushed rather than when it is popped, which can lock in a time that a cheaper route would beat.
  • Forgetting the stale-entry check, so outdated times relax edges again.
  • Pushing (depot, time) into heapq, which then orders by depot id instead of time.
  • Building the adjacency list for both directions when routes are one-way.
  • Reaching for Dijkstra when the problem allows negative weights.

How to explain it out loud

Fictional example

A walkthrough that names the assumption
Candidate
This is single-source shortest paths with non-negative weights, so Dijkstra fits. If weights could go negative I would switch to Bellman-Ford.
Candidate
I keep a dist array and a min-heap of time and depot. I pop the smallest, skip it if it is stale, and relax each outgoing route, pushing any improvement.
Candidate
The answer is the max of dist, or minus one if anything stayed infinite. That is O of V plus E log V time. If you want the actual route I will add a prev array.

Union-Find answers the simpler question of whether two nodes connect at all, with no distances involved. LFU Cache is a good next step if you want more practice keeping several structures in sync, which is what dist and the heap do here. Top K Frequent Elements drills the heap on its own, and Min Cost to Connect All Points uses a nearly identical pop-and-relax loop for Prim's algorithm, with a different relax rule.

Using Natively while you study

Graph problems are easier to drill with something that checks your reasoning. In practice runs on Mac or Windows, Natively can read the graph problem from a screenshot, or from the page itself through its Chrome extension, and write an approach and code you can compare against yours. Your spoken walkthrough is transcribed and saved with the session, so you can reread whether you stated the non-negative weight assumption. More on the AI interview assistant page.

Questions people ask

How does Dijkstra's algorithm work?

It keeps the best known distance to every node and repeatedly expands the unfinished node with the smallest distance, taken from a min-heap. Expanding a node relaxes its outgoing edges, recording any shorter distance it finds.

What is the time complexity of Dijkstra's algorithm?

With a binary heap it runs in O((V + E) log V) time and O(V + E) space. A version that scans an array for the minimum runs in O(V²), which can be better for very dense graphs.

Why doesn't Dijkstra's algorithm work with negative weights?

Its correctness rests on the closest unfinished node never getting closer later. A negative edge can make a longer path cheaper after a node was already finalized, so use Bellman-Ford when weights can be negative.

Should I use BFS or Dijkstra?

If every edge has the same weight, BFS gives shortest paths in O(V + E) with a plain queue. Once weights differ, you need Dijkstra's priority order.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP