Bitpath

Lesson 1 · Unit 03

Topological sort

Order tasks so every prerequisite comes first

11 exercisesabout 3 min

What you practise

  • In-degrees and Kahn's algorithm

Try a question from this lesson

Pick one

Socks go on before shoes. Trousers go on before shoes and before a belt. Which order works?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Kahn's algorithm

The in-degree of a node is the number of arrows pointing into it: the prerequisites it still waits for.

A node at 0 is ready. Take a ready node, add it to the order, and lower the in-degree of everything it points to. Whatever drops to 0 becomes ready in turn.

def kahn(adj, indeg, ready):
    order = []
    while ready:
        node = ready.pop()
        order.append(node)
        for nxt in adj[node]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                ready.append(nxt)
    return order
function kahn(adj, indeg, ready) {
  const order = [];
  while (ready.length > 0) {
    const node = ready.pop();
    order.push(node);
    for (const nxt of adj[node]) {
      indeg[nxt] -= 1;
      if (indeg[nxt] > 0) continue;
      ready.push(nxt);
    }
  }
  return order;
}
function kahn(
  adj: number[][], indeg: number[],
  ready: number[],
) {
  const order: number[] = [];
  while (ready.length > 0) {
    const node = ready.pop()!;
    order.push(node);
    for (const nxt of adj[node]) {
      indeg[nxt] -= 1;
      if (indeg[nxt] > 0) continue;
      ready.push(nxt);
    }
  }
  return order;
}

Python noteready.pop() takes from the end in O(1). Which ready node goes first does not matter: every choice gives a valid order.

TypeScript noteconst order: number[] = [] needs its annotation: an empty array gives TypeScript nothing to infer the item type from.

9 more exercises in the app

  • 2× type the answer
  • 3× multiple choice
  • 1× order the lines
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy