Fastest Route Through Only the Courses a Goal List Needs
Trees & GraphsModel answerLast updated
Given courses with durations, prerequisite links and a list of goal courses, compute the minimum time to finish the goals and their needed prerequisites, as total effort and as elapsed time.
Problem
A university catalog lists n courses. For each course you know how long it takes to complete, and you are given a list of prerequisite pairs (a, b) meaning course a must be fully finished before course b can start. You are also given a list of goal courses you want to complete.
Design an algorithm that reports the minimum time needed to complete all goal courses. You must take only the goals and the courses they transitively depend on. A course that is not a goal and is not a prerequisite (direct or indirect) of any goal must not influence the answer, even if it sits at the same depth in a topological ordering as a required course.
Because "minimum time" is ambiguous, state your scheduling model and give the answer for both readings:
- Total effort: one course at a time, so time is the sum of durations of the required courses.
- Elapsed time: any number of courses can run in parallel as soon as their prerequisites are finished, so time is the moment the last goal finishes.
Rules and edge cases
- The prerequisite graph should be a DAG. If a cycle is reachable from any goal (going backwards through prerequisites), no valid schedule exists and you must report that.
- A prerequisite shared by several goals counts once.
- Goals may live in disconnected parts of the graph. Handle them without inventing a dependency between them.
- One goal may itself be a prerequisite of another goal.
- Decide and state what happens with an unknown goal id (for example, reject the input).
- A cycle among courses that are not required should not cause failure.
What to deliver
Describe the algorithm, justify correctness for both interpretations, give the time and space complexity in terms of the required vertices and edges, and write the code. Be ready to discuss follow-ups such as limited parallelism (only k courses at once) and recovering the actual critical path.
Hints
Hint 1
Walk backwards from every goal along prerequisite edges to collect exactly the set of required courses. A visited set naturally handles shared prerequisites and separate components.
Hint 2
For total effort you only need the sum of durations over that required set, each course once. For elapsed time, the finish of a course is its own duration plus the latest finish among its prerequisites.
Hint 3
Do a DFS with three states (unvisited, in progress, done) on the required subgraph. Reaching an in-progress node means a cycle. Memoize finish times in the same pass so each node and edge is handled once.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Scheduling model
I would first confirm the assumptions with the interviewer:
- Durations are elapsed time per course and also the effort for it.
- Under the parallel model there is no cap on concurrent courses, and a course starts the instant all its prerequisites have finished.
- Under the sequential model one course runs at a time.
- Goals must all be completed; one goal may be a prerequisite of another.
- Unknown goal ids or a reachable cycle return an error (or a sentinel such as
-1).
Key idea
Only the ancestor closure of the goals matters: the goals plus everything reachable by following prerequisite edges backwards. Everything else is irrelevant. This is what prevents the common mistake of layering the whole graph topologically and taking the number of levels or summing whole levels, which would include unrelated courses.
Approach
- Build
prereqs[b]= list of courses that must precedeb. - Run a DFS from each goal along
prereqs, using three states per node: 0 = unvisited, 1 = in progress, 2 = done. - When DFS enters a node in state 1, a cycle is reachable from a goal. Report invalid.
- On finishing a node, compute
finish[v] = duration[v] + max(finish[p] for p in prereqs[v])(the max over an empty list is 0). Memoizing this makes it the DP over the DAG. - Collect the set of nodes that reach state 2; this is the required set.
Answers:
- Total effort = sum of
duration[v]over the required set. Shared prerequisites are counted once because each node appears once in the set. - Elapsed time with unlimited parallelism =
max(finish[g] for g in goals).
Why it is correct
For elapsed time, a course cannot start before its slowest prerequisite finishes, and with unlimited workers nothing else delays it, so the earliest finish satisfies the recurrence above. The last goal to finish determines the total. This equals the length of the longest duration-weighted path ending at a goal, which is the critical path. For total effort, every required course must be taken exactly once, so the sum is a lower bound and is achievable by any topological order.
Disconnected components need no special handling: each goal's DFS explores its own ancestors, and the maximum across goals gives elapsed time (components run side by side), while the sum covers all of them for effort. Forcing them into a single chain would wrongly add their times in the parallel model.
Code (Python)
import sys
from collections import defaultdict
def plan(n, duration, edges, goals):
# edges: (a, b) means a must be done before b
for g in goals:
if not (0 <= g < n):
raise ValueError("unknown goal")
prereqs = defaultdict(list)
for a, b in edges:
prereqs[b].append(a)
state = [0] * n
finish = [0] * n
sys.setrecursionlimit(max(1000, 2 * n + 10))
def dfs(v):
state[v] = 1
best = 0
for p in prereqs[v]:
if state[p] == 1:
return False # cycle
if state[p] == 0 and not dfs(p):
return False
best = max(best, finish[p])
finish[v] = duration[v] + best
state[v] = 2
return True
for g in goals:
if state[g] == 0 and not dfs(g):
return None # reachable cycle
required = [v for v in range(n) if state[v] == 2]
total_effort = sum(duration[v] for v in required)
elapsed = max((finish[g] for g in goals), default=0)
return total_effort, elapsed
For very deep graphs, convert the DFS to an iterative version with an explicit stack to avoid recursion limits.
Complexity
Let V' and E' be the required vertices and the edges among them. Time is O(V' + E') since each required node and edge is visited once. Space is O(V') for the states, finish times and recursion stack, plus the adjacency lists built from input (O(n + m) to build).
Worked example
Durations: A=3, B=2, C=4, D=1, X=10. Edges: A->C, B->C, C->D, and X is unrelated. Goal: D.
- Required set: {A, B, C, D}. X is excluded.
- Total effort: 3 + 2 + 4 + 1 = 10.
- Elapsed: finish(A)=3, finish(B)=2, finish(C)=4+3=7, finish(D)=8.
Note that X at the same level as A would have inflated both numbers had we used whole levels.
Common mistakes
- Summing or taking the max over entire topological layers, which pulls in unrelated courses.
- Counting a shared prerequisite twice in the effort total.
- Running Kahn's algorithm on the whole graph and failing because of a cycle in an irrelevant region.
- Adding the elapsed times of disconnected components instead of taking the maximum.
- Not marking in-progress nodes separately from finished ones, so cycles go undetected or diamonds are falsely flagged.
Follow-ups
- At most
kparallel courses: this is NP-hard in general (multiprocessor scheduling with precedence). A practical answer is list scheduling with a priority queue ordered by longest remaining path (critical-path-first), giving a good approximation. The lower bound ismax(critical path, ceil(total effort / k)). - Recover the critical path: store the argmax prerequisite for each node and walk back from the goal with the largest finish.
- Many queries on the same graph: memoize
finishglobally since it does not depend on the goal set; only the required set for effort changes.