KatInterview

Count Paths of Fixed Length in a DAG

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programminggraphstopological-sortdag

Last 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 ≤ 100
  • 0 ≤ len(edges) ≤ 1000
  • 0 ≤ u, v < n for each edge [u, v]
  • The graph is a valid DAG (no cycles)
  • 0 ≤ source < n
  • 0 ≤ 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 source will have all counts equal to 0

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.