Course Schedule II

Medium

Course Schedule II

Problem Statement

Given a schedule of courses with their prerequisites, return the order in which they can be finished. If a valid order exists, you must return the correct order; otherwise, return an empty array.

Each course is represented as

(course, prerequisites)
, where
(course, prerequisites[i])
means
course
is a prerequisite of
prerequisites[i]
. The same course may not be offered more than once but can be taken in any order. There may be multiple course schedules for a given graph.

This problem is a variation of the Topological Sort problem. However, in this case, if there's a cycle in the graph, we should return an empty array, as a valid order may not exist.

Rules and Constraints

  • 1 <= course1.length == course2.length <= 20
  • 0 <= prerequisite <= course.length - 1
  • Not every course has prerequisites, but you cannot take the same course more than once.

Input and Output

  • The input consists of two arrays:
    • course
      : an array of strings representing the courses
    • prerequisites
      : an array of arrays of integers, where each inner array contains course indices that are prerequisites of the corresponding course
  • The output should be an array of integers representing the order in which the courses can be finished. If a valid order does not exist, the output array will be empty.

Example

Input: {"input_data":[1,2,3]} Output: [1,2,3]

CompaniesGoogleMetaAmazon
JavaScript

Login to write code

Solve problems, verify your skills, and earn XP.