GRPH-P5

The smallest order

Practice 5 of 7Graphs11 tests

The problem

There are n tasks, numbered 0 to n − 1. Each edge (u, v) says task u must come before task v. Return an order of all n tasks that keeps every rule (a topological order). If several orders are possible, return the smallest: the one with the smallest first task; among those, the smallest second task; and so on. This is how Python compares lists. If no order is possible, return None.

edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
smallest_order(6, edges)       # [4, 5, 0, 2, 3, 1]
smallest_order(3, [(1, 0)])    # [1, 0, 2]
ring = [(0, 1), (1, 2), (2, 0)]
smallest_order(3, ring)        # None

Limits

  • Up to 100,000 tasks and 200,000 rules. A rule may be given twice.
  • Looking through all n tasks for the smallest ready one at every step costs about n² steps: far too slow. The big tests have 3 seconds each.

Builds on GRPH-5 Topological sort.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No edgesNot run
3A cycleNot run
4A cycle in one cornerNot run
5An edge given twiceNot run
6A chainNot run
7A small vertex freed lateNot run
8Many ready at onceNot run
9A chain of 100,000Not run
10100,000 vertices, 200,000 edgesNot run
11The same, with one edge backNot run