CodePark/ problems / Plan the Course Order
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Graphs and topological sort

Plan the Course Order

mediumabout 25 minutes in an interview

You need to take numCourses courses, labelled 0 up to numCourses - 1. A pair [a, b] in prerequisites says: course b has to be done before course a.

Return a study plan: an array that lists every course exactly once, where each course comes after all the courses it needs. If no plan can work, return [].

  • Often more than one plan works. Any of them is accepted.
  • numCourses is between 1 and 1,000. There are up to 2,000 pairs.
  • The same pair can show up more than once.
  • A course that names itself makes any plan impossible.
Input: numCourses = 4, prerequisites = [[2, 0], [2, 1], [3, 2]] Output: [0, 1, 2, 3][1, 0, 2, 3] is also correct.
Input: numCourses = 2, prerequisites = [[0, 1], [1, 0]] Output: []
Input: numCourses = 1, prerequisites = [] Output: [0]