KatInterview

Schedule Courses Given Prerequisites

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphkahn-algorithm

Last updated

Tests directed graph modeling, cycle detection, and topological ordering using Kahn's algorithm or DFS.

You are building a course scheduler. There are n courses numbered from 0 to n-1. Some courses have prerequisites: a prerequisite relationship [a, b] means that course b must be completed before you can take course a.

Your task is to determine whether it is possible to complete all courses, and if so, return any valid order in which the courses can be taken that respects all prerequisite relationships.

If no valid ordering exists (because the prerequisites form a cycle), return an empty list.

Input

  • n: an integer representing the number of courses
  • prerequisites: a list of prerequisite pairs [a, b] where b must be completed before a

Output

  • A list of n integers representing a valid course ordering
  • An empty list [] if no valid ordering exists

Constraints

  • 1 ≤ n ≤ 100,000
  • 0 ≤ len(prerequisites) ≤ 200,000
  • Each prerequisite pair contains valid course numbers in the range [0, n-1]
  • There may be duplicate prerequisite pairs
  • A course may appear as a prerequisite for itself (which creates an impossible cycle)

Notes

  • Multiple valid orderings may exist; you may return any one of them
  • If there are no prerequisites, any permutation of courses 0 through n-1 is valid
  • Disconnected components in the prerequisite graph should be handled correctly

Examples

Example 1

Input: find_course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])

Output: [0, 1, 2, 3]

Example 2

Input: find_course_order(2, [[1, 0], [0, 1]])

Output: []

Example 3

Input: find_course_order(3, [])

Output: [0, 1, 2]

Hints

Hint 1

Model the problem as a directed graph where each prerequisite pair creates an edge. What property must this graph have for a valid ordering to exist?

Hint 2

Track how many prerequisites each course has. Which courses can be taken immediately? Once you complete a course, how does that affect courses that depend on it?

Hint 3

Kahn's algorithm processes nodes with zero incoming edges iteratively. If you cannot process all n courses, what does that tell you about the graph structure?