AceYourInterviews
Checking sign-in…

104. Course Schedule II — Ordering

CoreConstruct a topological order by discharging incoming edge occurrences

Produce an order that contains every course exactly once and places every prerequisite before the course that depends on it. If no complete order is possible, return the documented empty result.

An order for only the acyclic portion is not a complete answer. Follow the course's tie-breaking convention when more than one ordering is possible.

Example 1

Input

n=5, pairs=[[1,0],[2,0],[3,1],[3,2]]

Output

[0,4,1,2,3] for this FIFO implementation

Explanation: Course 4 is initially ready and stays ahead of newly released courses 1 and 2. Other dependency-respecting permutations are valid.

Example 2

Input

n=4, pairs=[[1,0],[0,1],[3,2]]

Output

[]

Explanation: The algorithm may process 2 and 3, but the remaining cycle prevents a complete order.

Example 3

Input

n=0, pairs=[]

Output

[]

Explanation: An empty universe has one empty ordering; no course needs processing.

Constraints

  • 0 <= n <= 105
  • 0 <= edge occurrences <= 2 * 105
  • 0 <= vertex label < n
Hints
Hint 1

Turn each pair into prerequisite → dependent.

Hint 2

Track the number of unmet incoming occurrences and seed every zero.

Hint 3

Append FIFO removals, discharge outgoing occurrences, and reject an incomplete prefix.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

FIFO order includes isolated courses

5
[[1,0],[2,0],[3,1],[3,2]]
[0,4,1,2,3]