Leetcode #1462: Course Schedule IV
In this guide, we solve Leetcode #1462 Course Schedule IV in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Graph, Topological Sort
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
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.
Course 0 is not a prerequisite of course 1, but the opposite is true.
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
The time complexity is , and the space complexity is , where is the number of nodes. The space complexity is , where is the number of nodes.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.