#210

Course Schedule II

Medium
Depth-First SearchBreadth-First SearchGraph TheoryTopological SortGraph TheoryTopological SortBFS/DFS
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + p)
Space
O(1)
O(n)
💡

Intuition

Time O(n + p)Space O(n)

The optimal solution uses topological sorting to efficiently determine the order of courses based on their prerequisites. This method leverages graph theory to ensure we respect the dependencies.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build a graph using an adjacency list and track the in-degrees of each course.
  2. 2Step 2: Use a queue to process courses with zero in-degrees (no prerequisites).
  3. 3Step 3: While the queue is not empty, remove a course, add it to the result, and decrease the in-degrees of its neighbors. If any neighbor's in-degree reaches zero, add it to the queue.
  4. 4Step 4: If the result contains all courses, return it; otherwise, return an empty array (indicating a cycle).
solution.py23 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def findOrder(numCourses, prerequisites):
5    graph = defaultdict(list)
6    in_degree = [0] * numCourses
7    
8    for a, b in prerequisites:
9        graph[b].append(a)
10        in_degree[a] += 1
11    
12    queue = deque([i for i in range(numCourses) if in_degree[i] == 0])
13    order = []
14    
15    while queue:
16        course = queue.popleft()
17        order.append(course)
18        for neighbor in graph[course]:
19            in_degree[neighbor] -= 1
20            if in_degree[neighbor] == 0:
21                queue.append(neighbor)
22    
23    return order if len(order) == numCourses else []

Complexity note: The time complexity is O(n + p) where n is the number of courses and p is the number of prerequisites. We traverse each course and each prerequisite once.

  • 1Understanding graph representation is crucial for solving problems involving dependencies.
  • 2Topological sorting is a powerful technique for ordering tasks based on prerequisites.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.