Shortest Path in Undirected Graph with Unit Weights

medium

Given an undirected graph with V vertices (0 .. V-1) and edge list edges where every edge has weight 1, return an array dist with the shortest distance from source vertex 0 to every vertex (the fewest edges), or -1 if unreachable.

Hints

All edges cost the same, so the fewest-edges path is the shortest path.
BFS visits vertices in increasing distance order — use it from the source.
The level at which BFS first reaches a vertex is its distance.

Common doubts

Dijkstra's heap orders by weighted distance; with unit weights BFS's queue already yields vertices in distance order, so a plain queue suffices.
BFS reaches a vertex first via a shortest path, so its initial distance is final — re-visits would only be longer.
They keep the initial -1 since BFS never reaches them.

Interview follow-ups

Use 0-1 BFS with a deque — push 0-weight neighbours to the front, 1-weight to the back.
Then you need Dijkstra with a priority queue.

Fun facts

  • BFS is Dijkstra's algorithm specialised to unit weights — the heap collapses into a queue.
  • This is the engine behind word ladder and other 'fewest steps' puzzles.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 5, edges = [[0,1],[0,2],[1,3],[3,4]]
Output: [0, 1, 1, 2, 3]
BFS levels from vertex 0.
Example 2
Input: V = 4, edges = [[0,1],[2,3]]
Output: [0, 1, -1, -1]
Vertices 2 and 3 aren't reachable from 0.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - all edges have weight 1 - no self-loops or duplicate edges

Solve this problem →