Course Plan Builder with Already-Passed Classes
Trees & GraphsAuto-graded · 20 test casesLast updated
Build a valid course order from prerequisite pairs while skipping passed courses, using a topological sort with a fixed tie-break order and cycle detection.
Course Plan Builder
A university portal needs to produce a study plan. Each course may require other courses to be finished first. A student has already passed some courses, and those never need to be taken again.
You are given:
courses: a list of unique course IDs (strings). Every ID that appears inprereq_pairsis also in this list.prereq_pairs: a list of pairs[a, b]meaning courseamust be completed before courseb. Duplicate pairs may occur, and each copy counts separately.passed_courses: a list of course IDs the student has already passed. It may contain IDs that are not incourses.
Return the list of courses the student still has to take, in an order where each course comes after all of its prerequisites. Passed courses never appear in the output. If the plan cannot be completed because of a circular dependency, return an empty list.
Required ordering
Several valid orders can exist, so the answer must be the one produced by this exact procedure:
- For every course, count how many pairs in
prereq_pairshave it as the second element (b). Call this its requirement count. - Create a first-in-first-out line. Scan
coursesin the given order and add a course to the line if it is inpassed_coursesor its requirement count is 0. - Repeat until the line is empty:
- Remove the course
cat the front of the line. - If
cis not passed, append it to the output schedule. - Mark
cas handled. Passed courses count as handled from the very start. - Go through the pairs
[c, d]in the order they appear inprereq_pairs. Reduce the requirement count ofdby 1. If it reaches 0 anddis not handled, adddto the back of the line.
- Remove the course
- If any course in
courseswas never handled, return[]. Otherwise return the schedule.
A passed course is treated as available even if its own prerequisites are unmet, and the pairs leaving it are released when it reaches the front of the line. If every course is already passed, the result is [].
Constraints
1 <= len(courses) <= 1000- Course IDs are non-empty strings, and the IDs in
coursesare unique. - Every ID in
prereq_pairsappears incourses. passed_coursesmay contain IDs that are not incourses.- The output contains only courses that are not passed.
Examples
Example 1
Input: plan_courses(['CS101', 'CS102', 'CS103'], [['CS101', 'CS102'], ['CS102', 'CS103']], ['CS101'])
Output: ['CS102', 'CS103']
Example 2
Input: plan_courses(['A', 'B'], [['A', 'B'], ['B', 'A']], [])
Output: []
Hints
Hint 1
Treat each pair [a, b] as a directed edge a -> b and keep a count of unmet incoming edges for every course.
Hint 2
A FIFO queue gives the required order. Seed it by scanning `courses` in order, and remember that passed courses are seeded too, even though they are never output.
Hint 3
Reaching the front of the queue is what releases a course's outgoing edges. After the loop, any listed course that was never handled means a cycle, so return an empty list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a topological sort (Kahn's algorithm) with one twist: passed courses are always available, and they are never written to the output.
- Build an adjacency list from the pairs, and count for each course how many pairs point at it (its requirement count).
- Seed a FIFO queue by scanning
coursesin order. A course goes in if it is passed or has a requirement count of 0. - Pop courses one at a time. Append a popped course to the schedule unless it is passed. Then reduce the requirement count of each dependent course. When a count reaches 0 and the course has not been handled, enqueue it.
- After the queue empties, check that every listed course was handled. If one wasn't, it is on a cycle or depends on one, so return
[].
Why it is correct
- Valid order. A non-passed course is enqueued only when its count reaches 0. That means every pair pointing at it has been released by a course already popped, so all its prerequisites come earlier in the queue and therefore earlier in the schedule.
- Passed courses. They are seeded regardless of their own requirements, so their outgoing pairs are released as soon as they reach the front. The prerequisites they satisfy no longer block anything.
- Cycle detection. Courses on a cycle each wait on another course in the same cycle, so none of their counts can reach 0. They are never handled, and neither is anything that depends on them. The final check then returns
[]. - Determinism. The seeding order, the FIFO queue and the pair order fix the output. Because the procedure is fully specified, the result is unique.
Complexity
- Time: O(V + E), since each course is enqueued at most once and each pair is processed once.
- Space: O(V + E) for the adjacency list, the counts, the queue and the result.
Reference solution
from typing import List
from collections import defaultdict, deque
def plan_courses(courses: List[str], prereq_pairs: List[List[str]], passed_courses: List[str]) -> List[str]:
passed = set(passed_courses)
course_set = set(courses)
graph = defaultdict(list)
need = defaultdict(int)
for c in courses:
if c not in need:
need[c] = 0
for a, b in prereq_pairs:
graph[a].append(b)
need[b] += 1
line = deque()
for c in courses:
if c in passed or need[c] == 0:
line.append(c)
schedule = []
handled = set(passed)
while line:
cur = line.popleft()
if cur not in passed and cur in course_set:
schedule.append(cur)
handled.add(cur)
for nxt in graph[cur]:
need[nxt] -= 1
if need[nxt] == 0 and nxt not in handled:
line.append(nxt)
for c in courses:
if c not in handled:
return []
return schedule