Python coding

Course order, lowest number first

There are n courses numbered 0 to n - 1, and each pair [course, needs] in prereqs means needs must come before course. Return a list of all n courses in an order that respects every pair. Whenever several courses are ready (all their prerequisites already placed), place the lowest-numbered one next, so the answer is unique. If no valid order exists, return [].

Besides the tests, one large input (5,500 courses) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • course_order(4, [[1,0],[2,0],[3,1],[3,2]]) → [0,1,2,3]
  • course_order(3, [[0,1],[0,2]]) → [1,2,0]
  • course_order(2, [[0,1],[1,0]]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

This is a topological sort: Kahn's algorithm keeps placing a course whose in-degree has dropped to 0.

Hint 2

A FIFO queue gives a valid order, but not always the lowest-first one. Keep the ready courses in a min-heap (heapq) and pop the smallest each time.

Hint 3

If the order ends with fewer than n courses, the rest sit on a cycle or depend on one: return [].

Solution and why it works
pythonO(n log n + E), E = number of pairs · O(n + E)
import heapq

def course_order(n: int, prereqs: list[list[int]]) -> list[int]:
    adj, indeg = [[] for _ in range(n)], [0] * n
    for course, needs in prereqs:
        adj[needs].append(course)
        indeg[course] += 1
    ready = [i for i in range(n) if indeg[i] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        u = heapq.heappop(ready)
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                heapq.heappush(ready, v)
    return order if len(order) == n else []

This is Kahn's algorithm with a min-heap as its queue: the heap holds every course whose prerequisites are all placed, and popping it always gives the lowest ready number. A FIFO queue still gives a valid order, but for n = 5 with 0 → 2, 0 → 3, 4 → 1 it yields [0, 4, 2, 3, 1] instead of [0, 2, 3, 4, 1]. Check len(order) == n: a short order means a cycle.