Solution: Course Schedule II

Let's solve the Course Schedule II problem using the Topological Sort pattern.

Statement

You are given n courses, labeled from 0 to n - 1. Some courses have prerequisites, which are provided as a list of pairs: prerequisites[i] =[a,b]= [a, b]. To take course aa, you must first complete course bb.

Your task is to determine a valid order in which you can complete all the courses and return it as an array of course labels.

  • If there are multiple valid orderings, you can return any of them.

  • If it’s impossible to finish all courses (due to a cycle in prerequisites), return an empty array.

Note: There can be a course in the 00 to n1n−1 range with no prerequisites.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.