Shortest Path in DAG Using Topological Order in DSA C - Time & Space Complexity
We want to know how fast we can find the shortest path in a Directed Acyclic Graph (DAG) using topological order.
How does the time needed grow as the graph gets bigger?
Analyze the time complexity of the following code snippet.
void shortestPath(int src, int V, vector> adj[]) {
vector dist(V, INT_MAX);
dist[src] = 0;
stack st;
vector visited(V, false);
// Topological sort helper
for (int i = 0; i < V; i++) {
if (!visited[i]) dfs(i, adj, visited, st);
}
while (!st.empty()) {
int u = st.top(); st.pop();
if (dist[u] != INT_MAX) {
for (auto &edge : adj[u]) {
int v = edge.first, w = edge.second;
if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;
}
}
}
}
This code finds shortest paths from a source node in a DAG by first ordering nodes topologically, then relaxing edges in that order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: DFS calls for topological sort and edge relaxation loops.
- How many times: DFS visits each node and edge once; edge relaxation loops run once per node's outgoing edges.
As the number of nodes (V) and edges (E) grow, the work grows roughly with the sum of nodes and edges.
| Input Size (V, E) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 operations (10 for nodes + 15 for edges) |
| 100 nodes, 200 edges | About 300 operations (100 + 200) |
| 1000 nodes, 5000 edges | About 6000 operations (1000 + 5000) |
Pattern observation: The total work grows linearly with the number of nodes plus edges.
Time Complexity: O(V + E)
This means the time to find shortest paths grows linearly with the total number of nodes and edges in the graph.
[X] Wrong: "The algorithm takes O(V * E) time because it checks all edges for each node repeatedly."
[OK] Correct: Each edge and node is processed only once due to topological order and DFS, so the work adds up, not multiplies.
Understanding this linear time approach shows you can efficiently solve shortest path problems in DAGs, a key skill for many graph challenges.
"What if the graph had cycles? How would the time complexity and approach change?"
Practice
Solution
Step 1: Understand topological order in DAG
Topological order arranges vertices so that every directed edge goes from an earlier vertex to a later one, ensuring no cycles.Step 2: Use topological order for shortest path
Processing vertices in this order allows updating shortest distances without revisiting nodes, making the algorithm efficient.Final Answer:
It allows processing vertices in a linear order without revisiting nodes. -> Option BQuick Check:
Topological order = linear processing [OK]
- Thinking DAG has cycles
- Confusing topological order with sorting by weights
- Assuming it finds longest path by default
Solution
Step 1: Understand initialization for shortest path
Distances should start as very large values (infinity) to represent unknown paths.Step 2: Identify correct initialization
Using INT_MAX sets all distances to a large number, suitable for shortest path updates.Final Answer:
int dist[5]; for(int i=0; i<5; i++) dist[i] = INT_MAX; -> Option CQuick Check:
Initialize distances to INT_MAX [OK]
- Initializing distances to zero (wrong for shortest path)
- Using INT_MIN which is for max path, not min
- Using -1 which can cause incorrect comparisons
0 -> 1 (2), 0 -> 2 (4), 1 -> 2 (1), 1 -> 3 (7), 2 -> 3 (3)If we run shortest path from vertex 0 using topological order, what is the shortest distance to vertex 3?
Solution
Step 1: Find topological order and initialize distances
Topological order can be [0,1,2,3]. Initialize dist[0]=0, others = infinity.Step 2: Relax edges in topological order
From 0: dist[1]=2, dist[2]=4.
From 1: dist[2]=min(4,2+1)=3, dist[3]=2+7=9.
From 2: dist[3]=min(9,3+3)=6.Final Answer:
6 -> Option AQuick Check:
Shortest path to 3 = 6 [OK]
- Not updating dist[2] to 3 from 1->2 edge
- Ignoring better path from 2 to 3
- Using wrong topological order
for (int i = 0; i < V; i++) {
for (auto edge : adj[i]) {
int v = edge.first;
int weight = edge.second;
if (dist[i] + weight < dist[v])
dist[v] = dist[i] + weight;
}
}Assume
dist is initialized and adj is adjacency list.Solution
Step 1: Check loop order for shortest path in DAG
The outer loop must process vertices in topological order to ensure correct relaxation.Step 2: Identify the error in loop order
Looping from 0 to V-1 may not respect topological order, causing incorrect distance updates.Final Answer:
The outer loop should follow topological order, not 0 to V-1. -> Option AQuick Check:
Use topological order for outer loop [OK]
- Ignoring topological order in loops
- Mixing up edge weight usage
- Reversing adjacency list unnecessarily
0->1(5), 0->2(3), 1->3(6), 1->2(2), 2->4(4), 2->5(2), 2->3(7), 3->4(-1), 4->5(-2)Using shortest path with topological order from vertex 0, what is the shortest distance to vertex 5?
Solution
Step 1: Determine topological order and initialize distances
One topological order: [0,1,2,3,4,5]. Initialize dist[0]=0, others infinity.Step 2: Relax edges in order
From 0: dist[1]=5, dist[2]=3.
From 1: dist[3]=min(inf,5+6=11)=11, dist[2]=min(3,5+2=7)=3 (unchanged).
From 2: dist[4]=min(inf,3+4=7)=7, dist[5]=min(inf,3+2=5)=5, dist[3]=min(11,3+7=10)=10.
From 3: dist[4]=min(7,10+(-1)=9)=7 (unchanged).
From 4: dist[5]=min(5,7+(-2)=5)=5 (unchanged).Final Answer:
5 -> Option DQuick Check:
Shortest distance to 5 = 5 [OK]
- Ignoring negative weights in relaxation
- Not updating distances with better paths
- Wrong topological order causing errors
Ready to prove it?
Pass the test and this pattern moves unknown
