15% off all plans & roadmaps Use code
See plansLeetCode 1136 · Solution & editorial
You are given an integer n representing the number of courses labeled from 1 to n. You are also given a 2D integer array relations where relations[i] = [prevCoursei, nextCoursei] denotes that course prevCoursei must be taken before course nextCoursei.
Parallel Courses is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph BFS - Topological Sort (Kahn's Algorithm) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Master topological sorting using Kahn's BFS algorithm. Solve course schedule and build order problems.
The reference solution runs in O(|V| + |E|) time and O(|E|) space.
Parallel Courses has been reported in interviews at Google, Uber.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Parallel Courses is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph BFS - Topological Sort (Kahn's Algorithm) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.