‹ DS&A interview · Socratic
DSA · Graphs · #62

Course Schedule II

Module 55 · difficulty 3/5·30:00starts on first keystroke

There are `numCourses` courses labeled `0` to `numCourses - 1`. You are given `prerequisites` where `prerequisites[i] = [a, b]` means you must take course `b` before course `a`. Implement `findOrder(numCourses, prerequisites)` that returns **any valid ordering** of courses you should take to finish all of them. If it is impossible to finish all courses (a cycle exists), return an empty array `[]`.

Examples
  • numCourses = 2, prerequisites = [[1,0]] [0,1]Take course 0 first, then course 1.
  • numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] [0,1,2,3]0 has no prereqs; 1 and 2 depend on 0; 3 depends on both. [0,2,1,3] is also valid.
  • numCourses = 2, prerequisites = [[1,0],[0,1]] []0 and 1 depend on each other — a cycle, so no order exists.
Constraints
  • · 1 <= numCourses <= 2000
  • · 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • · prerequisites[i].length == 2
  • · 0 <= a, b < numCourses
  • · All [a, b] pairs are distinct
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.