Katkat

Schedule prerequisite classes with retakes

SnowflakeSoftware Engineer · Onsite

Last updated

This problem tests your ability to model dependencies using a Directed Acyclic Graph (DAG) and perform a topological sort while accounting for re-take conditions.

Problem Statement

You are building a course scheduling system. Students must complete prerequisite classes before enrolling in advanced ones. Some students may fail a course and need to retake it. You are given a list of courses, their prerequisites, and a list of courses the student has already passed.

A student can only take a course if all its prerequisites are in the 'passed' list. If a course is already in the 'passed' list, it does not need to be taken again. Your task is to return a valid sequence of courses that a student must complete to finish all target courses.

Function Signature

def get_schedule(courses, prerequisites, passed_courses):

  • courses: A list of all course IDs (strings).
  • prerequisites: A list of pairs (prereq, course), meaning prereq must be completed before course.
  • passed_courses: A set of course IDs that the student has already passed.

Return a list of courses in the order they must be taken. If it is impossible to complete the courses due to circular dependencies, return an empty list.

Examples

Example 1:

  • courses: ["CS101", "CS102", "CS103"]
  • prerequisites: [("CS101", "CS102"), ("CS102", "CS103")]
  • passed_courses: ["CS101"]
  • Result: ["CS102", "CS103"]

Example 2:

  • courses: ["A", "B"]
  • prerequisites: [("A", "B"), ("B", "A")]
  • passed_courses: []
  • Result: [] (Cycle detected)

Constraints

  • Number of courses <= 1000.
  • passed_courses may contain courses that are not in the current required list.
  • The result should only contain courses that have not been passed yet.

Hints

Hint 1

Model the courses and their prerequisites as a directed graph where edges represent dependencies.

Hint 2

Remove all courses that are already in 'passed_courses' from the graph, or mark them as pre-satisfied nodes.

Hint 3

Perform a topological sort (using Kahn's algorithm or DFS) to determine the order of the remaining required courses.

Follow-up questions

  • How would you modify your solution if a course could have multiple equivalent prerequisites (e.g., 'Take either A or B')?
  • If the student has a limit on how many courses they can take per semester, how would you group the output into semesters?
  • What is the time complexity of your solution in terms of V (courses) and E (prerequisite pairs)?