Search⌘ K
AI Features

Course Schedule II

Explore how to use topological sort to solve course scheduling problems involving prerequisites. Learn to identify valid course sequences or detect cycles that make completion impossible. This lesson guides you through defining the problem and practicing your solution in code.

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.

Constraints:

Let nn be the number of courses.

  • 1n15001 \leq n \leq 1500
  • 00 \leq prerequisites.length 1000\leq 1000
  • prerequisites[i].length ==2== 2
  • 0a, b<n0 \leq a, \space b < n
  • aba \neq b
  • All the pairs [a, b][a, \space b] are distinct.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Course Schedule II

1.

What is the course order if the following list of prerequisites and an integer n are given as input?

Select all that apply.

n = 7

prerequisites = [[1, 0], [1, 2], [2, 3], [3, 4], [4, 5]] Multi-select

A.

[1, 0, 2, 3, 4, 5, 6]

B.

[0, 2, 1, 6, 5, 4, 3]

C.

[0, 5, 6, 4, 3, 2, 1]

D.

[6, 5, 4, 3, 2, 0, 1]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in the following coding playground:

Java
usercode > CourseSchedule.java
import java.util.*;
class CourseSchedule{
public static List <Integer> findOrder(int n, int[][] prerequisites) {
// Replace this placeholder return statement with your code
return new ArrayList<>();
}
}
Course Schedule II