MediumDepth-First SearchBreadth-First SearchGraphTopological Sort

Course Schedule II

LeetCode
1 approach, code in all languages

There are numCourses courses labeled from 0 to numCourses - 1. You are given a list prerequisites where each entry [a, b] means course b must be completed before course a.

Return any ordering of courses that lets you finish all of them. If more than one valid ordering exists you may return any of them.

If it is impossible to finish every course because of a circular dependency, return an empty array.

Example 1

Input: numCourses = 2, prerequisites = [[1,0]]

Output: [0,1]

Course 1 depends on course 0, so course 0 must come first. The order [0, 1] finishes both.

Example 2

Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]

Output: [0,1,2,3]

Course 0 unblocks 1 and 2, and both feed into 3. The order [0, 1, 2, 3] respects every prerequisite (other valid orders exist).

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 <= a_i, b_i < numCourses
  • a_i != b_i
  • All the pairs [a_i, b_i] are distinct.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now