Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in Python: Topological Sort with a Queue (Kahn)

Practice O(V + E) Read the full explanation

You get numCourses courses, numbered 0 to numCourses - 1. You also get a list prerequisites of pairs [a, b]. A pair means you must finish course b before you start course a.

Return True if you can take all the courses in some order. If you can't, return False.

 

Example 1:

Input: numCourses = 5, prerequisites = [[1, 0], [2, 1], [4, 3], [4, 2]]
Output: True
Explanation: Each arrow goes from a course to a course that needs it:
    0 → 1 → 2 → 4
            3 → 4
Course 4 needs both 2 and 3.
Taking the courses in number order, from 0 to 4, works.

Example 2:

Input: numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 2], [1, 3]]
Output: False
Explanation: The arrows 1 → 2 → 3 → 1 form a loop.
Course 1 waits for course 3.
Course 3 waits for course 2.
Course 2 waits for course 1.
Course 0 is fine, but the other three can never start.

Example 3:

Input: numCourses = 3, prerequisites = []
Output: True
Explanation: No course has a prerequisite, so any order works.

 

Constraints:

  • 1 to 100,000 courses.
  • Up to 100,000 pairs.
  • Both courses in a pair are valid course numbers.
  • The two courses in a pair are different.
  • No pair appears twice.
STEP 1 OF 16
    Ctrl + Enter to check

    PYTHON · GRAPHS

    Course Schedule in Python, explained

    Problem overview

    The method canFinish receives numCourses and a list prerequisites. Each pair [a, b] means course b must be taken before course a. It returns True if all the courses can be finished and False otherwise.

    With numCourses = 2 and prerequisites = [[1, 0]], you take course 0 and then course 1, so the answer is True. With [[1, 0], [0, 1]] each course waits for the other, so neither can ever be taken and the answer is False.

    Approach: take what is free, and unlock what it leads to

    Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. All the courses can be finished exactly when you can line them up so that every arrow points forward. Such an order is called a topological order, and it exists exactly when the arrows form no cycle.

    Kahn's algorithm builds that order one course at a time:

    1. Count, for every course, how many prerequisites it still waits for. This is its in-degree, the number of arrows pointing into it.
    2. Put every course with a count of 0 into a queue. They can be taken now.
    3. Take a course from the queue. For each course that waits for it, lower that course's count by one. If a count reaches 0, the course is free: add it to the queue.
    4. Repeat until the queue is empty.

    Courses on a cycle wait for each other, so their counts never reach 0 and they never enter the queue. Neither does any course that needs one of them. So if the number of courses taken equals numCourses, there is no cycle. If it is smaller, there is one.

    Every pair is looked at once, when its first course is taken, so the work is proportional to the number of courses plus the number of pairs.

    Step by step

    1. Build the graph. graph is a list of numCourses empty lists made with a list comprehension. graph[b] will hold the courses that wait for course b.
    2. Create inDegree, a list of numCourses zeros. inDegree[a] counts the prerequisites of course a that haven't been taken yet.
    3. Loop over prerequisites with the variable prereq. Each pair becomes one arrow.
    4. Record the arrow. Append prereq[0] to graph[prereq[1]]: course prereq[1] comes first, and prereq[0] waits for it.
    5. Count the prerequisite. Add 1 to inDegree[prereq[0]].
    6. Create an empty deque named queue, for the courses that can be taken now. A deque adds at the back with append and removes from the front with popleft, both in constant time.
    7. Look at every course, with course over range(numCourses), and append the ones whose inDegree is 0. Any valid order starts with courses that need nothing. If there are none, every course waits for another one.
    8. Start taken at 0. It counts the courses we manage to take.
    9. Loop while queue is not empty. An empty deque counts as false, so while queue: is enough.
    10. Take the front course with popleft and add 1 to taken. Everything in the queue has all its prerequisites taken, so taking it is safe, and courses come out in a topological order.
    11. Visit the courses that wait for it, nextCourse over graph[course], and subtract 1 from inDegree[nextCourse].
    12. Free the ones that reach 0. When a count hits 0, the last prerequisite was just taken, so append nextCourse to the queue. A count reaches 0 only once, so each course enters the queue at most once.
    13. Return taken == numCourses.

    The solution in Python

    class Solution:
        def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
            graph = [[] for _ in range(numCourses)]
            inDegree = [0] * numCourses
            for prereq in prerequisites:
                graph[prereq[1]].append(prereq[0])
                inDegree[prereq[0]] += 1
            queue = deque()
            for course in range(numCourses):
                if inDegree[course] == 0:
                    queue.append(course)
            taken = 0
            while queue:
                course = queue.popleft()
                taken += 1
                for nextCourse in graph[course]:
                    inDegree[nextCourse] -= 1
                    if inDegree[nextCourse] == 0:
                        queue.append(nextCourse)
            return taken == numCourses
    

    Python details worth knowing

    • Build the lists with a comprehension. [[] for _ in range(numCourses)] creates a separate empty list for each course. Writing [[]] * numCourses repeats one list object, so every slot is the same list. After g = [[]] * 3 and g[0].append(1), g is [[1], [1], [1]]. With the comprehension, the same append gives [[1], [], []].
    • [0] * numCourses is safe for numbers. Integers are immutable, so inDegree[a] += 1 replaces one slot's value and doesn't touch the others.
    • Use a deque, not list.pop(0). Removing the first item of a list shifts all the others, which costs time proportional to the list's length. deque.popleft() doesn't. It comes from the collections module.

    Trace on the third example

    For numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], the arrays after the first loop are graph = [[1, 2], [3], [3], []] and inDegree = [0, 1, 1, 2]. Only course 0 starts in the queue. Each turn of the main loop then looks like this:

    Course takeninDegree afterwardsqueue afterwards
    0[0, 0, 0, 2][1, 2]
    1[0, 0, 0, 1][2]
    2[0, 0, 0, 0][3]
    3[0, 0, 0, 0][]

    Four courses were taken, which equals numCourses, so the result is True. Course 3 only entered the queue after both 1 and 2 were taken, because its count needed two decrements to reach 0.

    Complexity

    Time: with V courses and E pairs, building the graph is O(V + E). Each course enters the queue at most once and is taken once. Each pair is looked at once, when its first course is taken. In total that is O(V + E).

    Space: graph holds V lists and E entries, inDegree holds V counts, and the queue holds at most V courses, so the space is O(V + E).

    Edge cases and common mistakes

    • No prerequisites. Every count is 0, every course goes into the queue, and the result is True. For numCourses = 3 and prerequisites = [] the method takes 0, 1 and 2 and returns True.
    • A cycle that doesn't include every course. With numCourses = 3 and [[1, 0], [2, 1], [1, 2]], course 0 is free and gets taken, but courses 1 and 2 wait for each other. taken ends at 1, not 3, so the result is False. This is why the final check compares against numCourses instead of asking whether the queue ever ran.
    • Arrow direction. The pair [a, b] means b comes first. Storing the arrow as graph[a] holding b reverses the whole graph, and the counts then describe the wrong courses.
    • Queueing a course twice. Add a course only at the moment its count reaches exactly 0, not whenever the count is "small".
    • Sharing one list. Building graph with [[]] * numCourses mixes all the courses' lists together.

    Testing

    These results come from running the solution:

    numCoursesprerequisitesResult
    2[[1, 0]]True
    2[[1, 0], [0, 1]]False
    4[[1, 0], [2, 0], [3, 1], [3, 2]]True
    3[[1, 0], [2, 1], [1, 2]]False
    3[]True
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free