Problem 558378 · medium · Phase 05 Advanced Algorithms & Graphs

Is the Schedule Forced?

topological sort · uniqueness · hamiltonian path

A workshop has n steps numbered 0 .. n-1 and a list edges where [a, b] means step a must happen before step b. A supervisor proposes order, a list of all n steps.

Return True if order respects every constraint and it is the only ordering that does so. Return False if order violates a constraint, if some other valid ordering exists, or if the constraints are contradictory (contain a cycle).

Examples

Input:  n = 3, edges = [[0, 1], [1, 2]], order = [0, 1, 2]
Output: True

Input:  n = 3, edges = [[0, 1], [0, 2]], order = [0, 1, 2]
Output: False
Explanation: [0, 2, 1] is also valid, so the order is not forced.

Input:  n = 2, edges = [[0, 1]], order = [1, 0]
Output: False
Explanation: the order breaks the constraint.

Constraints

  • 1 <= n <= 10**4, 0 <= len(edges) <= 3 * 10**4, order is a permutation of 0 .. n-1
  • Target: O(V + E) time.

Goals

  • Verify a proposed ordering against precedence constraints
  • Recognise that a topological order is unique exactly when one node is ready at every step
Starting Python…