Skip to content

Course Schedule IV

Answer many "must u come before v?" questions by filling a full prerequisite table in topological order.

MediumTopological Sort
Solve on LeetCode

The problem

There are numCourses courses numbered 0 to numCourses - 1, and each pair [a, b] in prerequisites means course a must be taken before course b; the pairs never form a cycle. Prerequisites carry over, so if a comes before b and b comes before c, then a is a prerequisite of c too. For each query [u, v] in queries, answer whether u is a prerequisite of v, and return the answers as a list of booleans.

Input numCourses = 4, prerequisites = [[0, 1], [1, 2], [3, 2]], queries = [[0, 2], [2, 0], [3, 1]]

Output [true, false, false]

0 comes before 1, which comes before 2, so 0 is a prerequisite of 2. Nothing makes 2 come before 0, and 3 is needed only for 2, not for 1.

Input numCourses = 3, prerequisites = [[2, 0], [2, 1]], queries = [[2, 1], [0, 1]]

Output [true, false]

2 comes before both 0 and 1, but 0 and 1 don't depend on each other.

Key constraint: There are at most 100 courses but up to 10,000 queries, so it pays to work out every prerequisite relation once and answer each query in O(1).

How to spot the pattern

  • The rules are "before" relations that chain together, and the indirect ones count too.
  • Many queries ask about the same small graph, so precomputing every answer beats searching once per query.

The idea

Handle the courses in topological order: when you reach a course, all of its prerequisites have been handled, so its set of prerequisites is already complete. An edge from course u to course v then hands v everything: u itself plus every course that comes before u. Keep these relations in an n by n table, and each query becomes a single lookup.

Brute force: Run a fresh BFS from u for every query to see whether it reaches v, which costs O(Q * (V + E)) time and repeats the same searches.

Step by step

  1. 1Build the edges from each course to the courses that need it, and count each course's prerequisites (its indegree).
  2. 2Make an n by n table isPre, all false, and queue every course with indegree 0.
  3. 3Take a course u from the queue and, for each course v it unlocks, set isPre[u][v] and copy every true isPre[x][u] into isPre[x][v].
  4. 4Lower the indegree of each such v, and queue it when the indegree reaches 0.
  5. 5Answer each query [u, v] with isPre[u][v].

See the pattern move

The topological sort pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
        n = numCourses
        unlocks = [[] for _ in range(n)]  # course -> courses that need it first
        indegree = [0] * n
        for before, after in prerequisites:
            unlocks[before].append(after)
            indegree[after] += 1

        is_pre = [[False] * n for _ in range(n)]  # is_pre[a][b]: course a must come before course b
        ready = deque(c for c in range(n) if indegree[c] == 0)
        while ready:
            course = ready.popleft()  # all of its prerequisites are already in the table
            for nxt in unlocks[course]:
                is_pre[course][nxt] = True
                for earlier in range(n):
                    if is_pre[earlier][course]:
                        is_pre[earlier][nxt] = True  # a prerequisite of course is one of nxt too
                indegree[nxt] -= 1
                if indegree[nxt] == 0:
                    ready.append(nxt)

        return [is_pre[u][v] for u, v in queries]

Complexity

Time

O(V * (V + E) + Q)

Space

O(V^2)

Each edge is handled once and copies a column of V entries; the table has V^2 cells, and each of the Q queries is one lookup.

Watch out for

  • Reading the pairs backwards: here [a, b] means a comes first, the opposite of Course Schedule.
  • Recording only the direct prerequisites and missing the chained ones.
  • Searching the graph again for every query, which repeats the same work up to 10,000 times.

Follow-up questions

Is there a simpler way when there are this few courses?

Floyd-Warshall style: for every middle course k and every pair i, j, set isPre[i][j] when both isPre[i][k] and isPre[k][j] are true. It takes O(V^3), which is fine for 100 courses.

How could you speed up the table updates?

Store each course's prerequisites as a bitset. Passing them along an edge then becomes one bitwise OR instead of a loop over all courses.

In Hinglish

Topological order mein chalo: jab course u se v ka edge mile, toh v ko u aur u ke saare prerequisites mil jaate hain. Table ek baar bhar do, phir har query bas ek lookup hai.

Related problems