#1462
Course Schedule IV
MediumDepth-First SearchBreadth-First SearchGraph TheoryTopological SortGraph TraversalDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n³) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n³)Space O(n²)
The optimal solution uses a graph representation and performs a transitive closure using the Floyd-Warshall algorithm to determine reachability between all pairs of courses in O(n³) time, which is efficient given the constraints.
⚙️
Algorithm
4 steps- 1Step 1: Create a graph representation of the courses and their prerequisites.
- 2Step 2: Initialize a reachability matrix where reach[i][j] is true if course i is a prerequisite of course j.
- 3Step 3: Use the Floyd-Warshall algorithm to update the reachability matrix based on the prerequisites.
- 4Step 4: Answer each query in O(1) time using the reachability matrix.
solution.py15 lines
1# Full working Python code
2def canFinish(numCourses, prerequisites, queries):
3 reach = [[False] * numCourses for _ in range(numCourses)]
4 for a, b in prerequisites:
5 reach[a][b] = True
6
7 for k in range(numCourses):
8 for i in range(numCourses):
9 for j in range(numCourses):
10 reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j])
11
12 result = []
13 for u, v in queries:
14 result.append(reach[u][v])
15 return resultℹ
Complexity note: The time complexity is O(n³) due to the three nested loops in the Floyd-Warshall algorithm. The space complexity is O(n²) because we maintain a 2D reachability matrix.
- 1Understanding graph representation is crucial.
- 2Transitive relationships can be efficiently computed using algorithms like Floyd-Warshall.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.