15% off all plans & roadmaps Use code
See plansLeetCode 2050 · Solution & editorial
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
Parallel Courses III 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.
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 III 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.