KatInterview

Graph Toolkit for Scene and Dependency Graphs: Sort, Traverse, Route

Trees & GraphsModel answer
MediumModel answerTrees & Graphstopological-sortbfs-dfsdijkstra

Last updated

Implement topological sort, BFS, DFS and Dijkstra on a dependency graph, then discuss CSR versus adjacency lists, CPU/GPU parallel traversal, and deterministic testing.

A rendering engine represents its scene hierarchy, render-pass ordering and asset build steps as a directed graph. Vertices are numbered 0..n-1, and each edge is (u, v, w) with a weight w >= 0.

Implement the following on such a graph:

  1. Topological ordering of the vertices, with detection of cycles.
  2. Breadth-first search from a source, producing hop counts.
  3. Depth-first search from a source, producing a preorder visit list.
  4. Dijkstra's shortest paths from a source, producing distances.

Then discuss:

  • Time and space complexity of each algorithm.
  • How a CSR (compressed sparse row) layout compares with per-vertex adjacency lists.
  • How you would parallelize traversals on a CPU and on a GPU, avoiding contention between workers.
  • How you would make results deterministic so a test suite can compare them exactly.

Specify your assumptions: what happens on cycles, unreachable vertices, self-loops, parallel edges, invalid vertex ids and negative weights. Results must not depend on the order in which edges were supplied.

Hints

Hint 1

Pick one compact graph representation up front (offset array plus flat target/weight arrays) and sort each vertex's neighbor list. Every algorithm then has a canonical visiting order.

Hint 2

For topological sort, track in-degrees and repeatedly release vertices that reach zero. If you emit fewer than n vertices, a cycle exists. Use a min-heap for the ready set if you want a unique answer.

Hint 3

For DFS on deep hierarchies, store (vertex, next edge index) on an explicit stack instead of recursing. For Dijkstra, push duplicate heap entries and skip stale ones rather than implementing decrease-key.

Hint 4

For the parallel discussion, think in terms of frontiers: one synchronized step per BFS level or per Kahn layer. Resolve races with atomic claims or atomic min, and sort or canonicalize each frontier before the next step.