Course Schedule II

Medium Solved

Description

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1.

You are given an array prerequisites where prerequisites[i] = [a, b] indicates that you must take course b before course a.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Input format / Clarification:

  • Line 1: Integer numCourses
  • Line 2: JSON array of prerequisite pairs

Example 1:

Input:
2
[[1,0]]

Output:
[0,1]

Example 2:

Input:
4
[[1,0],[2,0],[3,1],[3,2]]

Output:
[0,2,1,3]

Example 3:

Input:
1
[]

Output:
[0]

Note:

Your program must print a JSON array representing one valid course order. If no valid order exists, print [].

Your Submissions

No submissions yet.

Discuss

Discuss topological sorting using BFS (Kahn’s Algorithm) or DFS cycle detection.

Test Cases