Course DependencyLoading saved progress…

Course Dependency

You're building a course planner. Each course may require other courses to be taken first — calculus before differential equations, intro before advanced. Given the total number of courses and the list of prerequisite pairs, decide whether a student can finish every course. The catch is circular requirements: if A needs B and B needs A, neither can ever be the "first" one taken, and the whole plan is impossible. This is the same shape as resolving build dependencies or package installs — a topological ordering exists only when there's no cycle.

Signature

// numCourses: courses are numbered 0, 1, ..., numCourses - 1
// prerequisites: each pair [course, prereq] means `prereq` must be taken before `course`
// returns: true if all courses can be completed, false if a cycle makes it impossible
function courseDependency(numCourses: number, prerequisites: number[][]): boolean;

Examples

// A linear chain: take 0, then 1, then 2. No cycle.
courseDependency(3, [[1, 0], [2, 1]]); // → true
//   [1, 0] means course 0 must come before course 1
//   [2, 1] means course 1 must come before course 2
// Course 0 needs 1, and course 1 needs 0 — a cycle. Neither can go first.
courseDependency(2, [[0, 1], [1, 0]]); // → false

Notes

  • Courses are 0 to numCourses - 1. A course can appear in zero, one, or many prerequisite pairs. Some courses may have no prerequisites and be required by nobody — those are always fine.
  • Edge direction matters. [course, prereq] reads "prereq before course." Treat it as a directed edge prereq → course. Flipping the direction silently inverts the dependency.
  • A cycle means impossible. The answer is true if and only if the directed graph has no cycle. Any cycle — length two, length ten, or a single self-loop [0, 0] — makes the plan unsatisfiable.
  • No prerequisites means true. An empty prerequisites list (or a graph with no cycle) is always satisfiable.
  • Don't worry about producing the order. You only return a boolean here — whether a valid order exists, not the order itself. Producing one is a natural extension (see the solution's Going further).
Loading editor…