Course Schedule IV solution explained
Course Schedule IV asks many "must u come before v?" questions on one prerequisite graph, so the efficient answer precomputes reachability once and then answers each query in O(1). Build, for every course, the set of all courses that must come before it, filling the sets in topological order; with bitsets that costs about O(n · e / 64) work, and Floyd–Warshall's O(n³) is a simpler fallback when n is small.
By Evin JohnPublished 8 min read
The problem in plain words
A school offers n courses numbered from 0. Each prerequisite pair [a, b] says course a has to be completed before course b. Requirements chain: if a is needed before b and b before c, then a is needed before c too. The pairs never form a loop. You also receive a list of queries, each a pair [u, v], and must answer true or false for each: is u required, directly or through a chain, before v?
| n | Prerequisites | Queries | Answers |
|---|---|---|---|
| 4 | [0,1], [1,2], [3,2] | [0,2], [2,0], [3,1], [3,2] | true, false, false, true |
| 3 | none | [0,1] | false |
| 5 | [0,1], [0,2], [1,3], [2,3], [3,4] | [0,4], [1,2], [4,0] | true, false, false |
| 2 | [1,0] | [1,0], [0,1] | true, false |
In the first example, 0 leads to 1 and 1 leads to 2, so 0 is required before 2. Course 3 is needed for 2 but has nothing to do with 1. In the third, 1 and 2 are siblings: both come after 0 and before 3, but neither is required for the other.
Clarify the sizes. If n is at most about a hundred, an O(n³) table is trivially fast. If n is in the thousands, you want something closer to O(n · e). Also ask how many queries there are, because that decides whether precomputing is worth it at all.
How this differs from the other course schedule problems
Earlier problems in this family ask whether all courses can be finished, which is cycle detection, or ask for one valid order, which is a topological sort. Here the order is guaranteed to exist, and the question is about reachability between specific pairs. The interviewer is checking whether you recognize transitive closure and can reason about the trade between per-query work and up-front work.
Slow approach: search for every query
Build an adjacency list from each course to the courses it unlocks. For a query [u, v], run BFS from u and return true if v shows up. Each search costs O(n + e), so q queries cost O(q · (n + e)). With ten thousand queries on a graph of a hundred courses and a few thousand edges, that is tens of millions of steps, much of it repeated because the same starting course appears in many queries.
from collections import deque
def required_before_slow(n, prereqs, queries):
unlocks = [[] for _ in range(n)]
for a, b in prereqs:
unlocks[a].append(b)
answers = []
for u, v in queries:
seen = [False] * n
queue = deque(unlocks[u])
found = False
while queue and not found:
c = queue.popleft()
if c == v:
found = True
elif not seen[c]:
seen[c] = True
queue.extend(unlocks[c])
answers.append(found)
return answersA cheap improvement is to cache by starting course: compute everything reachable from u once and reuse it for every query that starts at u. Take that idea all the way, computing the set for every course, and you arrive at the main approach.
Main approach: build ancestor sets in topological order
For each course v, keep before[v], the set of every course required before v. If a is a direct prerequisite of b, then before[b] includes a and everything in before[a]. That only works if before[a] is complete when you use it, so process courses in topological order with Kahn's algorithm: a course leaves the queue only after all of its prerequisites have been processed.
In Python, an integer works as a bitset of any length: bit k set means course k is required. Merging two sets is a single |, which runs over machine words rather than individual courses. A query [u, v] becomes a check of bit u in before[v].
from collections import deque
def required_before(n, prereqs, queries):
unlocks = [[] for _ in range(n)]
waiting = [0] * n
for a, b in prereqs:
unlocks[a].append(b)
waiting[b] += 1
before = [0] * n # bit k set: course k must come first
queue = deque(c for c in range(n) if waiting[c] == 0)
while queue:
a = queue.popleft()
for b in unlocks[a]:
before[b] |= before[a] | (1 << a)
waiting[b] -= 1
if waiting[b] == 0:
queue.append(b)
return [(before[v] >> u) & 1 == 1 for u, v in queries]function requiredBefore(n, prereqs, queries) {
const unlocks = Array.from({ length: n }, () => []);
const waiting = new Array(n).fill(0);
for (const [a, b] of prereqs) {
unlocks[a].push(b);
waiting[b]++;
}
const before = Array.from({ length: n }, () => new Uint8Array(n));
const queue = [];
for (let c = 0; c < n; c++) if (waiting[c] === 0) queue.push(c);
for (let head = 0; head < queue.length; head++) {
const a = queue[head];
for (const b of unlocks[a]) {
const row = before[b];
const src = before[a];
for (let k = 0; k < n; k++) if (src[k]) row[k] = 1;
row[a] = 1;
if (--waiting[b] === 0) queue.push(b);
}
}
return queries.map(([u, v]) => before[v][u] === 1);
}The Floyd–Warshall shortcut
When n is small, a reachability matrix filled by three nested loops is the fastest thing to write and very hard to get wrong. For each middle course k, any course that reaches k also reaches everything k reaches.
def required_before_matrix(n, prereqs, queries):
reach = [[False] * n for _ in range(n)]
for a, b in prereqs:
reach[a][b] = True
for k in range(n):
for i in range(n):
if reach[i][k]:
row_i, row_k = reach[i], reach[k]
for j in range(n):
if row_k[j]:
row_i[j] = True
return [reach[u][v] for u, v in queries]Complexity
| Approach | Precompute | Per query | Extra space |
|---|---|---|---|
| BFS per query | O(n + e) | O(n + e) | O(n + e) |
| BFS from every course | O(n · (n + e)) | O(1) | O(n²) |
| Topological order with bitsets | O(n + e · n / 64) | O(1) | O(n²) bits |
| Floyd–Warshall | O(n³) | O(1) | O(n²) |
The JavaScript version above merges arrays element by element, so its precompute is O(e · n). Packing rows into 32-bit words would recover the bitset speedup if an interviewer asks.
Edge cases to test
- No prerequisites: every query is false.
- A query in the reverse direction of a real chain, like [2, 0] when 0 leads to 2. It must be false.
- Two courses that share a common prerequisite but do not depend on each other.
- Diamond shapes, where two routes lead from u to v. The answer is still a single true.
- A query with u equal to v. In an acyclic graph no course is its own prerequisite, so false.
- Courses with no edges at all mixed in with a long chain.
Common mistakes
- Reading the pair backwards. [a, b] means a before b, and the query asks whether the first course is required for the second.
- Only checking direct prerequisites, which fails every chained case.
- Merging ancestor sets in index order instead of topological order, so a course copies an incomplete set.
- Writing Floyd–Warshall with the middle loop in the wrong position. The k loop has to be outermost.
- Using recursion without memoization, which repeats the same searches and can blow up on dense graphs.
Explaining your choice
Fictional example
- Candidate
- Each query is a reachability check. I could BFS per query, but the same start courses will repeat, so I would rather build the full closure once and answer each query by lookup.
- Candidate
- I will store, for each course, a bitset of everything required before it, and fill it in topological order so each prerequisite's set is final before I merge it.
- Candidate
- If n stays around a hundred I might just write Floyd–Warshall instead, since a million steps is nothing. Either way, queries cost constant time afterward.
Other problems in this batch
Loud and Rich also walks a DAG in topological order, but keeps only one best ancestor per node instead of the whole set. All Paths From Source to Target goes further and lists every route, not just whether one exists. Find All Possible Recipes applies the same in-degree counting to string-named items. Graph theory refreshers live on the data structure interview questions page.
Preparing with Natively
While you practice graph questions like this, Natively can read a screenshot of the statement and suggest whether to precompute or search per query, which is worth comparing with your own call after you make it. The transcript it keeps of a mock round, stored on your computer, shows whether you explained the trade between up-front and per-query work. Read about AI for coding interview practice.
Questions people ask
What is the best approach for Course Schedule IV?
Precompute the transitive closure once, then answer each query by lookup. Building each course's ancestor set in topological order with bitsets is fast, and Floyd-Warshall in O(n³) is a simple option when n is small.
Why not run BFS for every query?
It is correct but costs O(n + e) per query, and the same starting courses repeat across queries. When queries are numerous, one up-front closure is cheaper overall.
Does the order of the prerequisite pair matter?
Yes. A pair [a, b] means a must be taken before b, and a query [u, v] asks whether u is required before v. Reading either one backwards flips the answers.
How is Course Schedule IV different from Course Schedule I and II?
The earlier problems ask whether a valid order exists or ask for one such order. This one assumes no cycles and asks about reachability between specific pairs of courses.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
