InterviewLegend

Shortest Path

Alex Chen25 min readMedium

When every edge costs the same, you never reach for Dijkstra. Plain BFS already hands you the shortest path, no priority queue involved. It works because BFS visits nodes in order of distance, so the first time it touches any node, that's the shortest way there. You'll lean on this more than almost any other graph fact.

The guarantee comes from two things working together: the queue is FIFO, and every edge adds exactly 1 to the distance. Every node at distance d gets enqueued before any node at distance d+1, and since first-in means first-out, it also gets processed first. Picture the queue as concentric rings expanding from the start: ring 0 is the start, ring 1 its direct neighbors, ring 2 their neighbors, and outward from there.

Say the start S has neighbors A, B, C, all at distance 1, so all three enter the queue. When we process A, its unvisited neighbors get added, but they land BEHIND B and C. So B and C, both at distance 1, get processed before any distance-2 node ever does. That's the invariant that turns BFS into a shortest-path algorithm: the queue stays sorted by distance on its own, purely because equal-weight edges bump the distance by exactly 1.

The BFS shortest-path invariant: at any moment during the search, the queue holds nodes at distance d followed by nodes at distance d+1, and nothing else. So the first time you dequeue a node, its shortest path is already settled.

This falls apart the moment edges carry different weights. If A->X costs 1 but B->X costs 3, BFS can't order them right, and Dijkstra's algorithm is what you reach for instead.
What's inside
  • 1 problem, worked step by step
  • about 25 min

Premium lessonData Structures & Algorithms

Keep going with Premium.

All 78 lessons and 103 worked problems in this course, plus what 100 companies ask, pulled from 20,000+ candidate reports.

100 companies. Checked every month.

Unlock the full course

$49 a year · less than $1 a week · Cancel anytime