Skip to content
mlmentorship

Course Schedule II

Save the zero-indegree emission order, reject blocked prefixes, and distinguish any valid witness from lexicographic priority and independent verification.

Published · 18 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Course Schedule II

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonnegative course_count and prerequisite pairs [course, prerequisite] with valid IDs from 0 through course_count - 1. Output. Return every course exactly once in a valid completion order, or [] if no complete order exists. Rules. In each pair, the prerequisite must occur earlier than the course. Include courses absent from the pairs. Repeated pairs do not create additional courses. Any valid complete order is acceptable. Preserve the inputs; zero courses returns [] as valid success. Example. Four courses with pairs [[1, 0], [2, 0], [3, 1], [3, 2]] permit [0, 1, 2, 3]. The order [0, 2, 1, 3] is also valid; pairs [[0, 1], [1, 0]] instead require [].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Emit only zero-indegree courses; remove each outgoing edge and enqueue a neighbor exactly when its count reaches zero.

Problem trace

Append eligible courses to a saved order; return it only when every course appears

Append eligible courses to a saved order; return it only when every course appearsDequeue a ready course, append it to the order, and remove its outgoing requirements. Here zero releases one and two; three waits for both. Ready membership and saved order are separate state. Each course appears once, before its dependents. Different eligible choices can give another valid order. If a cycle leaves an incomplete prefix, return failure rather than that prefix.Requirements control eligibility;emission builds the witness0123Three needs both one and two; zerostarts ready.Seed the ready queueready0orderemptyDequeue 0; append it onceready12order0Dequeue 1; append it onceready2order01Dequeue 2; append it onceready3order012Dequeue 3; append it oncereadyemptyorder0123All four saved: return the completeorder.Changed condition: add a requirementfrom three to two23Saved zero, one; two and three remainblocked. Return an empty failureresult, not the prefix.
Read it this way: Dequeue a ready course, append it to the order, and remove its outgoing requirements. Here zero releases one and two; three waits for both. Ready membership and saved order are separate state. Each course appears once, before its dependents. Different eligible choices can give another valid order. If a cycle leaves an incomplete prefix, return failure rather than that prefix. If prerequisite two never emits, can emitting prerequisite one twice make course three ready?
Full interview answer 18 min read

Produce a complete course order in which every prerequisite appears before the course that requires it.

Problem

Input. A nonnegative course_count and prerequisite pairs [course, prerequisite] with valid IDs from 0 through course_count - 1.

Output. Return every course exactly once in a valid completion order, or [] if no complete order exists.

Rules. In each pair, the prerequisite must occur earlier than the course. Include courses absent from the pairs. Repeated pairs do not create additional courses. Any valid complete order is acceptable. Preserve the inputs; zero courses returns [] as valid success.

Example. Four courses with pairs [[1, 0], [2, 0], [3, 1], [3, 2]] permit [0, 1, 2, 3]. The order [0, 2, 1, 3] is also valid; pairs [[0, 1], [1, 0]] instead require [].

Picture

Reuse zero-indegree elimination. indegree counts unmet incoming edges; ready holds courses with none remaining.

The added state is order: append each course when dequeued, not while its requirements remain unresolved.

For edges 0 -> 1, 0 -> 2, 1 -> 3, and 2 -> 3:

Eventready afterwardorder
Seed zero-indegree courses[0][]
Emit 0 and remove its edges[1,2][0]
Emit 1 and remove its edge[2][0,1]
Emit 2 and remove its edge[3][0,1,2]
Emit 3[][0,1,2,3]

After course one, course three still has one unmet edge. Emitting it then would violate 2 -> 3.

Every emitted prefix respects prerequisites. Return it only when its length equals course_count. Edges below show remaining requirements; emitted nodes stay visible.

[0,2,1,3] is also valid. FIFO seed order and adjacency insertion order choose one witness, not a canonical order.

Problem trace

Append eligible courses to a saved order; return it only when every course appears

Input and goalReturn one valid order for completing every course.
Build the prerequisite DAGEdges are 0->1, 0->2, 1->3, and 2->3. Their indegrees are [0,1,1,2], so ready=[0].
order: []0123
Original dependency matrix
from\to01230-0->10->2-1---1->32---2->33----
examplecourse_count=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]]edgeMeaningmatrix cell is prerequisite -> courseindegree[0,1,1,2]ready[0]order[]
example
course_count=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]]
edge meaning
matrix cell is prerequisite -> course
indegree
[0,1,1,2]

Recognize it
Directed prerequisites require one valid linear order; a cycle is present when some vertex never reaches zero indegree.
Keep true
Every ready vertex has zero incoming edges from un-emitted vertices, and order is a valid topological prefix; each outgoing edge is removed exactly once.
Reuse it
Remove resolved requirements one edge at a time and enqueue exactly on transition to zero; retain the emitted prefix when an order, not just feasibility, is required.
Edges are 0->1, 0->2, 1->3, and 2->3. Their indegrees are [0,1,1,2], so ready=[0]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must 3 wait after 1 is emitted, and could 2 appear before 1?
Reference drawing

Problem trace

Append eligible courses to a saved order; return it only when every course appears

Append eligible courses to a saved order; return it only when every course appearsDequeue a ready course, append it to the order, and remove its outgoing requirements. Here zero releases one and two; three waits for both. Ready membership and saved order are separate state. Each course appears once, before its dependents. Different eligible choices can give another valid order. If a cycle leaves an incomplete prefix, return failure rather than that prefix.Requirements control eligibility;emission builds the witness0123Three needs both one and two; zerostarts ready.Seed the ready queueready0orderemptyDequeue 0; append it onceready12order0Dequeue 1; append it onceready2order01Dequeue 2; append it onceready3order012Dequeue 3; append it oncereadyemptyorder0123All four saved: return the completeorder.Changed condition: add a requirementfrom three to two23Saved zero, one; two and three remainblocked. Return an empty failureresult, not the prefix.
Execution trace
Input and goalReturn one valid order for completing every course.
Build the prerequisite DAGEdges are 0->1, 0->2, 1->3, and 2->3. Their indegrees are [0,1,1,2], so ready=[0].
order: []0123
Original dependency matrix
from\to01230-0->10->2-1---1->32---2->33----
examplecourse_count=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]]edgeMeaningmatrix cell is prerequisite -> courseindegree[0,1,1,2]ready[0]order[]
example
course_count=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]]
edge meaning
matrix cell is prerequisite -> course
indegree
[0,1,1,2]

Recognize it
Directed prerequisites require one valid linear order; a cycle is present when some vertex never reaches zero indegree.
Keep true
Every ready vertex has zero incoming edges from un-emitted vertices, and order is a valid topological prefix; each outgoing edge is removed exactly once.
Reuse it
Remove resolved requirements one edge at a time and enqueue exactly on transition to zero; retain the emitted prefix when an order, not just feasibility, is required.
Edges are 0->1, 0->2, 1->3, and 2->3. Their indegrees are [0,1,1,2], so ready=[0]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must 3 wait after 1 is emitted, and could 2 appear before 1?
Read it this way: Dequeue a ready course, append it to the order, and remove its outgoing requirements. Here zero releases one and two; three waits for both. Ready membership and saved order are separate state. Each course appears once, before its dependents. Different eligible choices can give another valid order. If a cycle leaves an incomplete prefix, return failure rather than that prefix. If prerequisite two never emits, can emitting prerequisite one twice make course three ready?

Code

from collections import deque

def find_order(course_count: int, prerequisites: list[list[int]]) -> list[int]:
   graph = [[] for _ in range(course_count)]
   indegree = [0] * course_count

   for course, prerequisite in prerequisites:
      graph[prerequisite].append(course)
      indegree[course] += 1

   ready = deque(course for course in range(course_count) if indegree[course] == 0)
   order = []
   while ready:
      course = ready.popleft()
      order.append(course)
      for next_course in graph[course]:
         indegree[next_course] -= 1
         if indegree[next_course] == 0:
            ready.append(next_course)

   return order if len(order) == course_count else []

For courses and stored edges, work and storage are . A cycle can block other downstream courses too. Queue exhaustion alone does not certify a complete order.

Change Priority or Check the Witness

Start from find_order. Two adjustable parts are ready-course selection and how the returned order is checked.

  1. Choose the smallest eligible ID.

    New task: Return the lexicographically smallest valid order.

    Picture and change: Replace FIFO removal with minimum-heap removal. Keep zero-indegree eligibility and every edge decrement.

    Code: Complete replacement:

    import heapq
    
    
    def lexicographic_course_order(course_count, prerequisites):
       graph = [[] for _ in range(course_count)]
       indegree = [0] * course_count
       for course, prerequisite in prerequisites:
          graph[prerequisite].append(course)
          indegree[course] += 1
       ready = [course for course in range(course_count) if indegree[course] == 0]
       heapq.heapify(ready)
       order = []
       while ready:
          course = heapq.heappop(ready)
          order.append(course)
          for next_course in graph[course]:
             indegree[next_course] -= 1
             if indegree[next_course] == 0:
                heapq.heappush(ready, next_course)
       return order if len(order) == course_count else []

    Check: For [[2,0],[1,0],[3,1],[3,2]], FIFO emits [0,2,1,3]; the heap emits [0,1,2,3].

    The smallest ready course can safely lead the remaining valid order. Choosing it repeatedly minimizes the first differing position.

    Use when: The output needs this explicit tie policy. Work becomes ; storage remains .

  2. Verify a proposed order.

    New task: Check a candidate containing hashable integer IDs without regenerating the source’s preferred witness.

    Picture and change: Confirm the entire unique course universe, then map each course to its position.

    Code: Complete independent verifier under the same prerequisite-ID contract:

    def valid_course_order(course_count, prerequisites, order):
       if len(order) != course_count or set(order) != set(range(course_count)):
          return False
       positions = {course: index for index, course in enumerate(order)}
       return all(
          positions[prerequisite] < positions[course]
          for course, prerequisite in prerequisites
       )

    Check: The diamond accepts [0,2,1,3] but rejects [0,1,3,2] because 2 -> 3 is reversed. With two courses, [0,0] fails completeness even without edges.

    Use when: Tests or consumers need a certificate, not one particular sequence. Expected work is , with auxiliary storage.

Rebuild Readiness

Does replacing FIFO with a heap change cycle detection?

Answer: No. Both emit only zero-indegree nodes and reject incomplete output. Priority changes witness order and cost, not eligibility.