Please use Laptop/Desktop or any other large screen for the Mock Interview Session.

Course Schedule - Print Roadmap



YouTube Video Thumbnail
Link

Watch above sample mock interview video to see how it works.
Login and Buy Premium to Start the Interview



Course Ordering Problem

Course Ordering Problem

Problem Statement

Suppose you have m courses labeled from 0 to m-1.

Some courses require others to be completed first. For instance, to enroll in course 2 you might need to finish course 1, represented as a pair: [2, 1].

Given the total number of courses and a list of prerequisite pairs, determine an order in which you can take all courses.

If multiple valid sequences are possible, returning any one of them is acceptable. If no valid ordering exists due to cyclic dependencies, return an empty list.

Examples

Example 1:

Input: 3, [[1,0]]
Output: [0,1,2]
Explanation: There are 3 courses. To take course 1, you must first complete course 0. Course 2 has no prerequisites, so one possible order is [0,1,2].
    

Example 2:

Input: 5, [[1,0],[2,0],[3,1],[4,3]]
Output: [0,1,3,4,2] or [0,2,1,3,4]
Explanation: 
Course 1 and 2 depend on course 0.
Course 3 depends on course 1.
Course 4 depends on course 3.
Multiple valid orders exist, such as [0,1,3,4,2] or [0,2,1,3,4].
    

Constraints

  • 1 ≤ m ≤ 2000
  • 0 ≤ number of prerequisite pairs ≤ 6000
  • Prerequisite pairs are given as a list of edges without duplicates