Python coding

Is it a prerequisite, even indirectly?

There are n courses numbered 0 to n - 1. Each pair [course, needs] in prereqs means needs must be finished before course. Prerequisites chain: if A is needed for B and B for C, then A is also a prerequisite of C. For each pair [a, b] in queries, answer whether a is a prerequisite of b, directly or indirectly. Return the answers as a list of booleans, in order.

The prerequisites never form a cycle, pairs may repeat, and no course is its own prerequisite. There can be a few hundred courses and thousands of queries.

Besides the tests, one large input (600 courses, 12,000 queries) with a ~250 ms limit (scaled to your device's speed): brute force won't pass.

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

A search per query repeats work thousands of times. Instead, compute once, for every course, the full set of courses that must come before it.

Hint 2

Process courses in topological order (Kahn): when you take a course, all its prerequisites are already complete, so pass its set, plus itself, to each course it unlocks.

Hint 3

A Python int works as a fast bitset: bit j set means course j comes before. Merging two sets is a single |.

Solution and why it works
pythonO(n + (E + q)·n / w), E = len(prereqs), q = len(queries), w = 64-bit word · O(E + n² / w)
from collections import deque


def is_prerequisite(n: int, prereqs: list[list[int]], queries: list[list[int]]) -> list[bool]:
    unlocks, indeg = [[] for _ in range(n)], [0] * n
    for course, needs in prereqs:
        unlocks[needs].append(course)
        indeg[course] += 1
    before = [0] * n                         # bit j of before[c]: j must come before c
    queue = deque(c for c in range(n) if indeg[c] == 0)
    while queue:
        u = queue.popleft()                  # every prerequisite of u is already merged in
        for v in unlocks[u]:
            before[v] |= before[u] | 1 << u
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    return [bool(before[b] >> a & 1) for a, b in queries]

Kahn's algorithm reaches a course only after all its prerequisites, so by then their sets are complete and one merge per prerequisite pair builds every answer; each query is then a bit test. Searching the graph once per query redoes the same walk thousands of times. The trap is merging in any other order: a course merged before its own prerequisites are complete passes on a partial set.