Shortest Path in DAG Using Topological Order in DSA C# - Time & Space Complexity
We want to understand how the time needed to find the shortest path in a Directed Acyclic Graph (DAG) changes as the graph grows.
Specifically, how does the algorithm's work increase when the number of nodes and edges increases?
Analyze the time complexity of the following code snippet.
// Find shortest paths in DAG using topological order
void ShortestPathDAG(int V, List<(int, int)>[] graph, int src) {
int[] dist = new int[V];
for (int i = 0; i < V; i++) dist[i] = int.MaxValue;
dist[src] = 0;
var topoOrder = TopologicalSort(V, graph);
foreach (var u in topoOrder) {
if (dist[u] != int.MaxValue) {
foreach (var (v, w) in graph[u]) {
if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;
}
}
}
}
This code finds shortest paths from a source node to all others in a DAG by first sorting nodes topologically, then relaxing edges in order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over all nodes and their outgoing edges to update distances.
- How many times: Each node is visited once in topological order, and each edge is checked once during relaxation.
As the number of nodes (V) and edges (E) grow, the algorithm visits each node once and checks each edge once.
| Input Size (V, E) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | ~25 operations (10 + 15) |
| 100 nodes, 200 edges | ~300 operations (100 + 200) |
| 1000 nodes, 5000 edges | ~6000 operations (1000 + 5000) |
Pattern observation: The work grows roughly in proportion to the sum of nodes and edges.
Time Complexity: O(V + E)
This means the time needed grows linearly with the number of nodes plus the number of edges in the graph.
[X] Wrong: "The algorithm checks every possible path, so it must be exponential time."
[OK] Correct: Because the graph is acyclic and we use topological order, each edge is relaxed only once, avoiding repeated work on paths.
Understanding this time complexity shows you can analyze graph algorithms that smartly avoid repeated work by using orderings like topological sort.
This skill helps you explain why some graph problems can be solved efficiently despite many possible paths.
"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 all edges go from earlier to later vertices, 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 CQuick Check:
Topological order = linear processing [OK]
- Thinking topological order works with cycles
- Confusing shortest path with longest path
- Assuming edges are sorted by weight
Solution
Step 1: Understand distance initialization
Distances should start as infinity (int.MaxValue) except the source, to represent unknown paths.Step 2: Check code correctness
int[] dist = new int[5]; for(int i = 0; i < 5; i++) dist[i] = int.MaxValue; correctly sets all distances to int.MaxValue using a loop. int[] dist = new int[5] {0, 0, 0, 0, 0}; sets all to zero, which is incorrect. int[] dist = new int[5]; dist.Fill(int.MaxValue); uses a non-existent Fill method. int[] dist = new int[5]; for(int i = 0; i < 5; i++) dist[i] = 0; sets all to zero, which is wrong.Final Answer:
int[] dist = new int[5]; for(int i = 0; i < 5; i++) dist[i] = int.MaxValue; -> Option AQuick Check:
Initialize distances to max value [OK]
- Setting all distances to zero
- Using non-existent array methods
- Not initializing distances before algorithm
0 -> 1 (2), 0 -> 2 (4), 1 -> 2 (1), 1 -> 3 (7), 2 -> 4 (3), 3 -> 4 (1)If we run the shortest path algorithm from vertex 0 using topological order, what is the shortest distance to vertex 4?
Solution
Step 1: Find topological order and initialize distances
Topological order can be [0,1,2,3,4]. 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)=3, dist[3]=2+7=9.
From 2: dist[4]=3+3=6.
From 3: dist[4]=min(6,9+1=10)=6.Final Answer:
6 -> Option BQuick Check:
Shortest distance to 4 = 6 [OK]
- Not updating distances after relaxation
- Using wrong topological order
- Ignoring better paths through intermediate nodes
int[] dist = new int[V];
for(int i = 0; i < V; i++) dist[i] = int.MaxValue;
dist[source] = 0;
foreach(int u in topologicalOrder)
{
foreach(var edge in graph[u])
{
int v = edge.Item1;
int weight = edge.Item2;
if(dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
What is the bug in this code?
Solution
Step 1: Analyze distance update condition
The code adds dist[u] + weight without checking if dist[u] is int.MaxValue, which can cause overflow.Step 2: Identify missing check
Before adding weight, code should check if dist[u] != int.MaxValue to avoid invalid calculations.Final Answer:
No check if dist[u] is int.MaxValue before adding weight -> Option AQuick Check:
Check dist[u] before adding weight [OK]
- Ignoring overflow from adding to int.MaxValue
- Assuming topological order is always computed
- Thinking initialization is missing
0->1(3), 0->2(6), 1->2(4), 1->3(4), 1->4(11), 2->3(8), 3->4(-4), 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
Possible topological order: [0,1,2,3,4,5]. Initialize dist[0]=0, others = infinity.Step 2: Relax edges in order
From 0: dist[1]=3, dist[2]=6.
From 1: dist[2]=min(6,3+4=7)=6, dist[3]=3+4=7, dist[4]=3+11=14.
From 2: dist[3]=min(7,6+8=14)=7.
From 3: dist[4]=min(14,7+(-4)=3)=3.
From 4: dist[5]=3+2=5.Final Answer:
5 -> Option DQuick Check:
Shortest distance to 5 = 5 [OK]
- Ignoring negative edge weights
- Not updating distances after better path found
- Wrong topological order causing incorrect results
Ready to prove it?
Pass the test and this pattern moves unknown
