KatInterview

Smallest-First Course Ordering With Cycle Check

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphheap

Last updated

Produce the lexicographically smallest valid course order from prerequisite pairs, or an empty list if a cycle makes it impossible, using a topological sort with a min-heap.

A school offers course_count courses, numbered 0 through course_count - 1. You are given a list of requirement pairs [c, p], each meaning that course p must be completed before course c can be taken.

Return a complete ordering in which every course appears exactly once and every requirement is respected. If no such ordering exists because the requirements contain a cycle, return an empty list.

Choosing among valid orderings. Several valid orderings may exist, and you must return exactly one: the lexicographically smallest one. Compare two orderings position by position, and the one with the smaller course number at the first differing position wins. Equivalently, whenever several courses could be taken next, pick the one with the smallest number.

Special cases.

  • A requirement [c, c] is a cycle, so the answer is [].
  • The same requirement may appear more than once. Duplicates do not change the answer.
  • If course_count is 0, return [].
  • Courses that appear in no requirement must still be included in the ordering.

Constraints

  • 0 <= course_count <= 10^5
  • 0 <= len(requirements) <= 2 * 10^5
  • Each requirement is a pair [c, p] with 0 <= c, p < course_count.
  • The function returns a list of integers: the ordering, or [] if it is impossible.

Examples

Example 1

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

Output: [0, 1]

Example 2

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

Output: [0, 1, 2, 3]

Example 3

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

Output: []

Hints

Hint 1

Treat each requirement as a directed edge from the prerequisite to the course that depends on it, and track how many unmet prerequisites each course has.

Hint 2

A course can be taken when its count of unmet prerequisites reaches zero. Repeatedly take such courses and update the courses that depend on them.

Hint 3

To get the lexicographically smallest order, keep the currently available courses in a min-heap instead of a plain queue. If you finish with fewer than course_count courses, a cycle exists.