Parallel Courses

Medium

Topics
GraphTopological SortBFS

You are given n courses labelled 0 to n - 1 and a list of edges where edges[i] = [a, b] means course a must be taken before course b.

In one semester you may take any number of courses, as long as every prerequisite of each one was completed in an earlier semester.

Return the minimum number of semesters needed to take all courses, or -1 if it is impossible.

Example 1

012
semester 1
Any number of courses can be taken at once as long as their prerequisites are done, so each semester clears one whole layer of the graph. The shaded nodes are the first layer, and counting layers gives 2 semesters.
Directed edges [before, after]; the arrow points at the later course.
Input:  n = 3, edges = [[0,1],[0,2]]
Output: 2
Explanation: Take course 0 in semester 1, then courses 1 and 2 together in semester 2.

Example 2

012
The shaded nodes are the first layer, and counting layers gives -1, because a cycle leaves 3 course(s) unreachable.
Input:  n = 3, edges = [[0,1],[1,2],[2,0]]
Output: -1
Explanation: The three courses form a cycle, so no valid order exists.

Constraints

  • 1 <= n <= 5000
  • 0 <= edges.length <= 5000
  • edges[i].length == 2
  • All pairs are distinct
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because a semester has unlimited width, the only thing that costs time is depth: the answer is the number of levels in a layered topological order, which equals the longest prerequisite chain. Run Kahn's algorithm but drain the queue one full level at a time and count the levels. If some course never reaches in-degree zero it sits on a cycle, so the answer is -1.

Approach

  1. Build an adjacency list and an in-degree array from the edge list.
  2. Seed a queue with every course of in-degree zero. Those are exactly the courses available in semester 1.
  3. Process the queue level by level: snapshot its current size, pop that many courses, and decrement their neighbours' in-degrees, pushing any that reach zero. Increment the semester counter once per level.
  4. Count how many courses were popped in total. If that is less than n, a cycle blocked the rest, so return -1; otherwise return the level count.
from collections import deque

class Solution:
    def minimumSemesters(self, n, edges):
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for a, b in edges:
            adj[a].append(b)
            indeg[b] += 1
        q = deque(i for i in range(n) if indeg[i] == 0)
        semesters = 0
        taken = 0
        while q:
            semesters += 1
            for _ in range(len(q)):
                cur = q.popleft()
                taken += 1
                for nxt in adj[cur]:
                    indeg[nxt] -= 1
                    if indeg[nxt] == 0:
                        q.append(nxt)
        return semesters if taken == n else -1

Dry Run

n = 3, relations 0 -> 1 and 0 -> 2
  indeg [0, 1, 1]      frontier [0]
  semester 1   take [0]      done 1   next frontier [1, 2]
  semester 2   take [1, 2]   done 3   next frontier []
  done 3 of 3
answer 2   --  not 3, even though there are 3 courses
n = 3, relations 0 -> 1, 1 -> 2, 2 -> 0
  indeg [1, 1, 1]      frontier []     -- nothing has in-degree 0
  the loop never runs: semesters 0, done 0
answer -1
The whole point is that the answer counts LEVELS, not nodes. Courses 1 and 2 have
no dependency on each other, so they are taken together, and returning the number
of courses processed would give 3 instead of 2.
The frontier is rebuilt as a whole list per semester rather than popped one at a
time, which is what keeps the levels separate. Reading a queue length live inside
the loop instead merges semesters together and undercounts.
`done == n` is the cycle check and it is not optional. The cyclic graph above
fails loudly only because it is entirely cyclic; a graph with a cycle plus a free
course would drain the free part and return a small positive number that looks
like a real answer.
An edge case worth stating: with no relations at all, n = 3 answers 1, not 0. Three
independent courses still take one semester.

Complexity

  • Time — O(V + E) — each course and edge is handled once.
  • Space — O(V + E) for the adjacency list, in-degrees, and queue.

Common Pitfalls

  • Reading the queue length inside the loop instead of snapshotting it first merges semesters together and undercounts the answer.
  • Do not return the number of popped courses. The answer is the number of levels, not the number of nodes.
  • The cycle check is mandatory. Without the taken == n test a cyclic graph silently returns a small positive number.
  • An isolated course with no prerequisites still needs one semester, so an empty edge list answers 1, not 0.

Full Solution — all languages

class Solution:
    def minimumSemesters(self, n, edges):
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for a, b in edges:
            adj[a].append(b)
            indeg[b] += 1
        frontier = [i for i in range(n) if indeg[i] == 0]
        semesters = 0
        done = 0
        while frontier:
            semesters += 1
            nxt = []
            for course in frontier:
                done += 1
                for after in adj[course]:
                    indeg[after] -= 1
                    if indeg[after] == 0:
                        nxt.append(after)
            frontier = nxt
        return semesters if done == n else -1
Asked at Netflix Snowflake
SensAI
Beta
Tap the mic to stop voice mode