Graph Toolkit for Scene and Dependency Graphs: Sort, Traverse, Route
Trees & GraphsModel answerLast 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:
- Topological ordering of the vertices, with detection of cycles.
- Breadth-first search from a source, producing hop counts.
- Depth-first search from a source, producing a preorder visit list.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Contract and assumptions
- Vertices are
0..n-1; edge endpoints are validated and out-of-range ids raise an error. - Weights are non-negative. Negative weights make Dijkstra incorrect, so they are rejected.
- Output depends only on the set of edges, never on input order. This is achieved by sorting each vertex's neighbors.
- Unreachable vertices get
-1(BFS) orinf(Dijkstra). A cyclic graph has no topological order, so the function returnsNone. - Self-loops count as cycles for topological sort. Parallel edges are legal: in-degree counts each copy, and Dijkstra uses the cheapest.
Memory layout: CSR vs adjacency lists
CSR stores three flat arrays: offsets[n+1], targets[m], weights[m]. The neighbors of u are targets[offsets[u]:offsets[u+1]].
| CSR | List of lists / linked nodes | |
|---|---|---|
| Memory | (n+1) + 2m words, no per-node overhead | Pointer and header overhead per vertex or edge |
| Scan speed | Sequential, cache and prefetch friendly, coalesced on GPU | Pointer chasing, poor locality |
| Mutation | Expensive (rebuild or leave gaps) | Cheap insert/delete |
| Parallel use | Easy to partition by edge ranges; read-only so no locks | Needs care around concurrent mutation |
For a scene or pass graph that is built once and traversed many times, CSR is the right choice. Keep an adjacency-list or edge-buffer form only for editing, then rebuild CSR with a counting sort (O(V + E)) plus a per-row sort for canonical order.
Algorithms
Topological sort (Kahn). Compute in-degrees, put all zero in-degree vertices in a ready set, then repeatedly remove one, append it to the output, and decrement its successors. Using a min-heap as the ready set yields the lexicographically smallest order, which is unique and testable. If the output has fewer than n vertices, the leftover vertices lie on or behind a cycle.
BFS. Process the graph level by level from the source. The first time a vertex is discovered is along a path with the fewest edges, because levels are processed in nondecreasing distance.
DFS. Keep an explicit stack of (vertex, next edge position). This mirrors the recursive call stack exactly, so the preorder matches the recursive version, and deep hierarchies (long chains) cannot hit a recursion limit.
Dijkstra. Keep a binary heap of (distance, vertex). Pop the smallest entry; if it is stale (larger than the recorded distance) skip it; otherwise relax its outgoing edges and push improved entries. With non-negative weights, the popped vertex's distance is final because any alternative route must pass through a vertex with a key at least as large. Ties in the heap break by vertex id, so output is deterministic.
Complexity
| Algorithm | Time | Extra space |
|---|---|---|
| CSR build | O(V + E) plus row sorting, O(E log d) | O(V + E) |
| Topological sort (heap) | O((V + E) log V); O(V + E) with a plain FIFO | O(V) |
| BFS, DFS | O(V + E) | O(V) |
| Dijkstra (lazy heap) | O((V + E) log E) | O(V + E) |
Code (Python)
import heapq
from math import inf
class CSR:
def __init__(self, n, edges):
self.n = n
off = [0] * (n + 1)
for u, v, w in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError("vertex id out of range")
if w < 0:
raise ValueError("negative weight")
off[u + 1] += 1
for i in range(n):
off[i + 1] += off[i]
rows = [[] for _ in range(n)]
for u, v, w in edges:
rows[u].append((v, w))
self.off = off
self.to, self.w = [], []
for r in rows:
r.sort() # canonical neighbor order
for v, w in r:
self.to.append(v)
self.w.append(w)
def topo_order(g):
indeg = [0] * g.n
for v in g.to:
indeg[v] += 1
ready = [u for u in range(g.n) if indeg[u] == 0]
heapq.heapify(ready)
out = []
while ready:
u = heapq.heappop(ready)
out.append(u)
for k in range(g.off[u], g.off[u + 1]):
v = g.to[k]
indeg[v] -= 1
if indeg[v] == 0:
heapq.heappush(ready, v)
return out if len(out) == g.n else None
def bfs_levels(g, s):
dist = [-1] * g.n
dist[s] = 0
cur = [s]
while cur:
nxt = []
for u in cur:
for k in range(g.off[u], g.off[u + 1]):
v = g.to[k]
if dist[v] < 0:
dist[v] = dist[u] + 1
nxt.append(v)
cur = nxt
return dist
def dfs_preorder(g, s):
seen = [False] * g.n
seen[s] = True
order = [s]
stack = [[s, g.off[s]]]
while stack:
top = stack[-1]
u, k = top
if k == g.off[u + 1]:
stack.pop()
continue
top[1] += 1
v = g.to[k]
if not seen[v]:
seen[v] = True
order.append(v)
stack.append([v, g.off[v]])
return order
def dijkstra(g, s):
dist = [inf] * g.n
dist[s] = 0
pq = [(0, s)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # stale entry
for k in range(g.off[u], g.off[u + 1]):
v, nd = g.to[k], d + g.w[k]
if nd < dist[v]:
dist[v] = nd
heapq.heappush(pq, (nd, v))
return dist
Parallelization
Shared idea: frontier-synchronous steps. BFS levels and Kahn "layers" (all vertices whose in-degree is currently zero) are naturally parallel. Process one frontier in parallel, barrier, then build the next.
CPU (multi-threaded)
- Split the frontier into chunks, or split by edge ranges so one huge-degree vertex doesn't stall a thread.
- Claim a vertex with an atomic compare-and-swap on its distance or visited flag. Only the winner appends it.
- Give each thread a private output buffer and concatenate them, which avoids contention on a shared queue.
- For topological layers, atomically decrement successor in-degrees; the thread that brings a count to zero adds the vertex to the next layer.
- DFS is inherently sequential. Parallelize across independent roots or subtrees, or use a different algorithm when you only need reachability.
GPU
- CSR gives coalesced reads. Assign a thread per low-degree vertex, a warp or block per high-degree vertex to balance load.
- Build the next frontier with a prefix-sum compaction rather than a global atomic counter, which would serialize.
- Dijkstra's heap does not map well. Use delta-stepping (bucketed relaxation) or Bellman-Ford style rounds, relaxing with
atomicMinon distances. - Beware wasted work and the cost of many kernel launches on deep, narrow graphs (long chains); a CPU path can win there.
Contention: prefer private buffers plus merge, atomics only on the claim itself, and avoid false sharing by padding per-thread counters.
Determinism in tests
- Parallel schedules vary, so make the result canonical. Sort each next frontier by vertex id before the next step, or write
atomicMinon a packed(distance, parent id)key so ties resolve identically. - Floating-point addition is not associative, so parallel reductions can differ in the last bits. Use integer or fixed-point weights, or compare with a tolerance and keep the tie-break on integers.
- Tests: compare every parallel result with the sequential reference; run with 1, 2 and N threads; shuffle the edge input; use fixed random seeds; and add property checks (every edge goes forward in a topological order,
dist[v] <= dist[u] + wfor all edges, BFS distance equals Dijkstra with unit weights). - Include edge cases: empty graph, single vertex, isolated vertices, self-loop, two-node cycle, parallel edges, disconnected components, a 10^6-long chain, and a negative weight that must raise.
Common mistakes
- Recursive DFS that overflows on deep hierarchies.
- Forgetting that
len(order) < nis the cycle test, or returning a partial order as if valid. - Running Dijkstra with negative weights.
- Implementing decrease-key on a library heap that doesn't support it, instead of lazy deletion.
- Claiming a parallel traversal is deterministic without canonicalizing frontier order and tie-breaks.