Count Paths of Fixed Length in a DAG
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests dynamic programming on graphs, topological ordering, and systematic state-space enumeration with path-length constraints.
You are given a directed acyclic graph with n nodes numbered from 0 to n-1, represented by a list of directed edges. Each edge is given as [u, v], meaning there is a directed edge from node u to node v.
Write a function that computes, for every node and every path length from 0 to max_len, how many distinct paths exist from a given source node to that node using exactly that many edges.
Return a 2D list result where result[node][length] is the number of distinct paths from source to node that traverse exactly length edges.
Constraints
1 ≤ n ≤ 1000 ≤ len(edges) ≤ 10000 ≤ u, v < nfor each edge[u, v]- The graph is a valid DAG (no cycles)
0 ≤ source < n0 ≤ max_len ≤ 50- If the same edge appears multiple times in the input, each occurrence represents a distinct edge and contributes separately to path counts
- Nodes unreachable from
sourcewill have all counts equal to0
Examples
Example 1
Input: count_dag_paths(4, [[0, 1], [0, 2], [1, 3], [2, 3]], 0, 2)
Output: [[1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 2]]
Example 2
Input: count_dag_paths(5, [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4]], 0, 4)
Output: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 2, 0]]
Example 3
Input: count_dag_paths(4, [[0, 1], [1, 2], [0, 2]], 0, 2)
Output: [[1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 0, 0]]
Hints
Hint 1
Consider what it means for a path to have exactly k edges: it must pass through exactly k+1 nodes (counting the source).
Hint 2
A path of length k+1 is formed by extending a path of length k with one additional edge. How can you build counts incrementally?
Hint 3
Processing nodes in topological order ensures that when you compute counts for a node, all its predecessors have already been finalized.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that any path with exactly k+1 edges can be decomposed into a path with exactly k edges followed by one more edge. This naturally leads to a two-dimensional dynamic programming formulation.
We define dp[u][k] as the number of distinct paths from the source to node u that use exactly k edges. The base case is dp[source][0] = 1, representing the empty path (zero edges) that stays at the source. All other entries start at zero.
The recurrence relation is: for each edge (u, v), we have dp[v][k+1] += dp[u][k]. In other words, every path to v of length k+1 is formed by taking some path to u of length k and appending the edge (u, v).
To ensure correctness, we must process nodes in an order where all predecessors of a node are finalized before we use that node to update its successors. Topological ordering on the DAG guarantees this property. We use Kahn's algorithm to compute the topological order, then iterate through nodes in that order, propagating path counts forward along outgoing edges.
Why It Works
In a topological order, every directed edge points from an earlier node to a later node in the sequence. When we reach node u in the iteration, all nodes with edges pointing to u have already been processed. This means dp[u][k] is complete for all k before we use it to update successors.
By induction: the source correctly has one path of length zero. For any other node v and length k+1, every path is counted exactly once when we process the edge from its second-to-last node.
Complexity
Time complexity: O((n + m) × L) where n is the number of nodes, m is the number of edges, and L is max_len. The topological sort takes O(n + m), and the DP phase visits each (node, length) pair and processes each edge once per length value.
Space complexity: O(n × L) for the DP table, plus O(n + m) for the adjacency list and auxiliary structures used in topological sorting.
Solution
from collections import deque
from typing import List
def count_dag_paths(n: int, edges: List[List[int]], source: int, max_len: int) -> List[List[int]]:
# Build adjacency list and compute indegrees
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
# Topological sort using Kahn's algorithm
q = deque([i for i in range(n) if indeg[i] == 0])
topo_order = []
while q:
node = q.popleft()
topo_order.append(node)
for neighbor in adj[node]:
indeg[neighbor] -= 1
if indeg[neighbor] == 0:
q.append(neighbor)
# Initialize DP table
dp = [[0] * (max_len + 1) for _ in range(n)]
dp[source][0] = 1 # One path of length 0: the empty path at source
# Process nodes in topological order
for u in topo_order:
for length in range(max_len):
paths = dp[u][length]
if paths == 0:
continue
# Extend all paths ending at u with length edges
for v in adj[u]:
dp[v][length + 1] += paths
return dp