CodeBlanks Logo Icon CodeBlanks

Dependency order

Find a dependency order in a DAG.

Dependency order

Topological sorting orders nodes in a directed acyclic graph (DAG) by their dependencies. Each node comes after all nodes it depends on.

It is used wherever dependencies exist, like build tasks or course prerequisites. If a cycle exists, no order is possible.

Adjacency list

The graph is represented as an adjacency list of each node's successors. For example graph[0] = [1, 2] shows edges from 0 to 1 and 2.

This representation clearly expresses dependencies. Each node lists only the nodes that depend on it.

Practice init_graph function

Write init_graph(). Return the adjacency list. Print it with print(init_graph()).

Starter code

solution.py
def init_graph():
    # Return adjacency list

Sample solution

solution.py
def init_graph():
    # Return adjacency list
    return [[1, 2], [3], [3], []]
print(init_graph())

Expected output

[[1, 2], [3], [3], []]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In which graph is topological sort possible?

  • Directed acyclic (DAG) Correct answer
  • Undirected
  • Directed cyclic
  • Fully connected

Explanation: Topological sort is possible in a DAG.

2 Edge definition

Question
graph[0] = [____, 2]
Answer
graph[0] = [1, 2]

Explanation: 1 is right.

3 Dependency order: match the terms

Term Meaning
graph[0] 0 to 1,2
graph[1] 1 to 3
graph[2] 2 to 3
graph[3] no exit

All lessons in Advanced