Course Schedule IV — LeetCode 1462 Python Solution
- Problem
- #1462
- Pattern
- Topological Sort
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
Example
- Input
- numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
- Output
- [false,true]
- Explanation
- The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Python solution
class Solution:
def checkIfPrerequisite(
self, n: int, prerequisites: List[List[int]], queries: List[List[int]]
) -> List[bool]:
f = [[False] * n for _ in range(n)]
for a, b in prerequisites:
f[a][b] = True
for k in range(n):
for i in range(n):
for j in range(n):
if f[i][k] and f[k][j]:
f[i][j] = True
return [f[a][b] for a, b in queries]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^3) |
| Space | O(n^2), where n is the number of nodes auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 1462. Course Schedule IV is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1462. Course Schedule IV?
- LeetCode 1462. Course Schedule IV is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1462. Course Schedule IV?
- The Python solution on this page runs in O(n^3).
- What is the space complexity of LeetCode 1462. Course Schedule IV?
- The Python solution on this page uses O(n^2), where n is the number of nodes auxiliary space.
- What topics does LeetCode 1462. Course Schedule IV cover?
- LeetCode 1462. Course Schedule IV is tagged Depth-First Search, Breadth-First Search, Graph and Topological Sort on LeetCode.