KatInterview

BFS Unweighted Shortest Path with Ancestor Tracking

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbfsgraph-traversalshortest-path

Last updated

Perform breadth-first traversal on an unweighted graph to compute shortest distances and record parent pointers for path reconstruction.

Given a directed or undirected unweighted graph with n vertices labeled from 0 to n - 1, represented as an adjacency list adj, perform a Breadth-First Search starting from a source node s.

Compute and return a list containing two arrays: [dist, parent].

  1. dist: An array of length n where dist[i] is the minimum number of edges needed to travel from s to vertex i. If vertex i is not reachable from s, dist[i] should be -1. The distance to the starting node s is 0.
  2. parent: An array of length n tracking the predecessor of each node on the discovered shortest path from s. parent[i] is the index of the vertex that first discovered i. If i == s or i is unreachable, set parent[i] to -1.

Constraints

  • $1 \le n \le 10^5$
  • len(adj) == n
  • $0 \le s < n$
  • $0 \le \text{adj}[u][i] < n$ for all valid $u, i$
  • Total number of edges across all vertices is at most $2 \cdot 10^5$.
  • Graphs may contain disconnected components, self-loops, or multiple edges.

Examples

Example 1

Input: bfs_shortest_paths(6, [[1, 2], [0, 3], [0, 3], [1, 2, 4], [3], []], 0)

Output: [[0, 1, 1, 2, 3, -1], [-1, 0, 0, 1, 3, -1]]

Example 2

Input: bfs_shortest_paths(5, [[1], [0, 2], [1], [4], [3]], 0)

Output: [[0, 1, 2, -1, -1], [-1, 0, 1, -1, -1]]

Example 3

Input: bfs_shortest_paths(4, [[], [], [], []], 2)

Output: [[-1, -1, 0, -1], [-1, -1, -1, -1]]

Hints

Hint 1

Initialize both the distance and parent arrays with -1 to handle unreachable nodes automatically.

Hint 2

Use a queue (e.g., `collections.deque`) for level-by-level traversal.

Hint 3

Mark nodes as visited as soon as you push them into the queue to avoid redundant processing and maintain linear time complexity.