Interview concept

What is Dijkstra's algorithm?

Dijkstra's algorithm computes the shortest path from a source node to every other node in a weighted graph with non-negative edges. It repeatedly expands the closest unvisited node using a priority queue.

Interview concept

How it works

How it works

Keep tentative distances, always expand the nearest unvisited node, and relax each of its neighbors.

Priority queue

A min-heap makes selecting the closest node efficient, giving O((V plus E) log V) time.

Limitations

It requires non-negative weights; for graphs with negative edges use Bellman-Ford instead.

Interview concept

Worked example: shortest path from A to D

Edges: A-B 4, A-C 1, C-B 2, B-D 1, C-D 5, all non-negative. Track tentative distances and always expand the closest unvisited node.

Start

Distance A = 0 and every other node is infinity. The priority queue holds (0, A).

Expand A

Relax its edges: B becomes 4 and C becomes 1.

Expand C (distance 1)

B improves to 1 + 2 = 3, and D becomes 1 + 5 = 6.

Expand B (distance 3)

D improves to 3 + 1 = 4.

Expand D (distance 4)

The shortest A to D path is 4, along A, C, B, D. With a binary heap the algorithm runs in O((V + E) log V).

Interview concept

Responsible use

Use any live AI assistant only where interview, workplace, school, and platform rules allow it. Do not use generated answers to misrepresent your skills, experience, or authorship.

FAQ

Common questions.

Why does Dijkstra need non-negative weights?

A negative edge can make an already-finalized node reachable more cheaply later, breaking the greedy assumption.

What data structure speeds up Dijkstra?

A binary or Fibonacci heap used as a priority queue selects the nearest node efficiently.