Let be a weighted directed acyclic graph with edges and vertices. Given and a source vertex in , which one of the following options gives the worst case time complexity of the fastest algorithm to find the lengths of shortest paths from to all vertices that are reachable from in ?
A
Step-by-Step Solution
Insight: Shortest paths in a Directed Acyclic Graph (DAG) can be found in linear time using topological sorting, bypassing the need for priority queues or multiple passes.
Exam route: Recognize the graph is a DAG. Recall that topological sort + single-pass relaxation takes time, which is . Select A.
Learning route:
Step 1: Recognize the graph type. The problem explicitly states the graph is a weighted Directed Acyclic Graph (DAG). This is the crucial condition that allows a faster algorithm than Dijkstra's or Bellman-Ford.
Step 2: Perform a topological sort of the vertices. This linearizes the graph such that all directed edges go from left to right. This step takes time using DFS or Kahn's algorithm.
Step 3: Initialize the distance to the source vertex as 0, and all other vertices as .
Step 4: Process each vertex in topological order. For each outgoing edge with weight , relax the edge: if , update .
Step 5: Because we process vertices in topological order, by the time we reach any vertex , all possible paths leading into have already been fully relaxed. Thus, each vertex and each edge is processed exactly once. The relaxation step takes time.
Step 6: Total time complexity is .
Tempting wrong path: Defaulting to Dijkstra's algorithm () or Bellman-Ford () because they are more commonly memorized. This fails to leverage the DAG property, which guarantees no back-edges and allows a single linear pass.
Verification: Topological sort visits each vertex and edge once. Relaxation visits each vertex and edge once. Total operations are proportional to , confirming .