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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | No edges | Not run | |
| 3 | A cycle | Not run | |
| 4 | A cycle in one corner | Not run | |
| 5 | An edge given twice | Not run | |
| 6 | A chain | Not run | |
| 7 | A small vertex freed late | Not run | |
| 8 | Many ready at once | Not run | |
| 9 | A chain of 100,000 | Not run | |
| 10 | 100,000 vertices, 200,000 edges | Not run | |
| 11 | The same, with one edge back | Not run |