1041. Course Schedule II — Return Order

MediumGraphsTopological SortBFSGraph

There are n courses labeled 0..n-1. Each edge [a, b] means course b must be taken before course a. Return a valid order in which to take all courses; if several exist, return the lexicographically smallest. Return an empty array if it is impossible (a cycle exists). The input is JSON {n, edges}.

Input: JSON {n, edges}.

Output: Array — a valid course order, or empty.

Examples

Example 1
Input: {"n":4,"edges":[[1,0],[2,0],[3,1],[3,2]]}
Output: [0,1,2,3]
Explanation: Lexicographically smallest valid order.
Example 2
Input: {"n":2,"edges":[[1,0],[0,1]]}
Output: []
Explanation: Cyclic prerequisites.
Example 3
Input: {"n":1,"edges":[]}
Output: [0]
Explanation: Single course.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →