KatInterview

Fastest Route Through Only the Courses a Goal List Needs

Trees & GraphsModel answer
HardModel answerTrees & Graphsgraphtopological-sortdag

Last 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:

  1. Total effort: one course at a time, so time is the sum of durations of the required courses.
  2. 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.