Skip to content
BytePatterns

Order the Build Steps

EasyGraphs#topological-sort#indegree~20m

Problem

A build has n steps numbered 0 to n - 1, and deps lists pairs [a, b] meaning step a must finish before step b starts. Return an order that runs every step after all of its prerequisites. If several orders are valid, any of them is accepted. If the dependencies loop so that no order exists, return an empty list.

Examples

Input:  n = 4, deps = [[0, 1], [0, 2], [1, 3], [2, 3]]
Output: [0, 1, 2, 3]
Why:    0 goes first, 1 and 2 only need 0, and 3 waits for both (running 2 before 1 is valid too)
Input:  n = 3, deps = [[0, 1], [1, 2], [2, 0]]
Output: []
Why:    each step waits on another step in a loop, so none can ever start
Input:  n = 3, deps = []
Output: [0, 1, 2]
Why:    edge case, with no dependencies every order works

Hints

0 / 3

Stuck on the idea rather than the code? Topological Sort covers it.