Problem 1462

Abstract / Summary

Given course prerequisites, determine if it is possible to finish all courses.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1462.py

class Solution:
    def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
        all = [ [ False ] * numCourses for _ in range(numCourses) ]
        for a, b in prerequisites:
            all[a][b] = True

        for mid in range(numCourses):
            for a in range(numCourses):
                if all[a][mid]:
                    for b in range(numCourses):
                        all[a][b] |= all[mid][b]

        for a, b in queries:
            yield all[a][b]
14 lines | 552 bytes | submitted March 6, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (100k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Graph
  • Topological Sort
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of determining whether one course is a prerequisite of another for a set of queries. It builds a complete prerequisite relationship matrix for all courses and then answers each query by looking up the pre-computed result. The algorithm follows a classic transitive-closure approach using a boolean adjacency matrix.

Initialization of the adjacency matrix

The first step creates a square matrix all of size numCourses × numCourses. Every entry is initially set to False, indicating that no prerequisite relationship is known.

all = [ [ False ] * numCourses for _ in range(numCourses) ]

Recording direct prerequisites

The input list prerequisites contains pairs [a, b] meaning course a must be taken before course b. Each pair is stored directly in the matrix, marking the corresponding entry as True.

for a, b in prerequisites:
    all[a][b] = True

If the prerequisites list is empty, the matrix remains entirely False, correctly representing the absence of any direct dependencies.

Computing the transitive closure

To capture indirect prerequisite relationships (e.g., a → mid → b), the code runs a three-level nested loop that implements the Floyd-Warshall algorithm for boolean matrices. The outer loop iterates over each possible intermediate course mid. For each mid, the middle loop scans all possible start courses a. The inner loop updates the relationship from a to every possible end course b whenever a path through mid exists.

for mid in range(numCourses):
    for a in range(numCourses):
        if all[a][mid]:
            for b in range(numCourses):
                all[a][b] |= all[mid][b]

The conditional if all[a][mid]: acts as a guard that skips the innermost loop when there is no known path from a to mid. This early-exit check reduces unnecessary work, especially in sparse prerequisite graphs. The use of the in-place bitwise OR operator |= updates the matrix without allocating new structures, keeping memory usage low.

The algorithm correctly handles edge cases such as self-prerequisite cycles. Since the matrix is never initialized with True on the diagonal, a course is not considered its own prerequisite unless a cycle is explicitly introduced via the input. The transitive-closure process will propagate such cycles, and the final matrix will reflect them accurately.

Answering the queries

After the closure matrix is ready, each query [a, b] is answered by yielding the boolean value stored at all[a][b]. The use of a generator (yield) provides a lazy sequence of results, which can be consumed efficiently by the caller.

for a, b in queries:
    yield all[a][b]

If the queries list is empty, the generator produces no output, which aligns with the expectation of returning an empty result set. When a query references courses that have no prerequisite relationship, the corresponding entry remains False, and the generator yields False.

Edge-case handling

  • Zero courses: When numCourses is 0, the matrix comprehension creates an empty list, and all subsequent loops execute zero iterations, resulting in an empty generator output.
  • Duplicate prerequisite entries: Assigning True to an already True cell is idempotent, so duplicate pairs do not affect correctness.
  • Disconnected subgraphs: Courses that belong to isolated components retain False entries for relationships outside their component, which the closure algorithm respects.
  • Queries with out-of-range indices: The code assumes that query indices are valid according to the problem constraints; within those bounds, the lookup is safe.

Performance optimizations observed

The implementation leverages several techniques to keep execution efficient:

  • The matrix is built with a list comprehension, which is faster than repeatedly appending rows.
  • Direct assignment of True for known prerequisites avoids extra checks during the closure phase.
  • The guard if all[a][mid]: prevents the innermost loop from running when there is no path through the current intermediate node, cutting down the number of inner-loop iterations dramatically for sparse graphs.
  • In-place updates using the |= operator eliminate the need for temporary matrices, reducing both time spent on copying data and memory overhead.
  • Yielding results as a generator avoids constructing an intermediate list of booleans, allowing the caller to process answers on the fly.
written by openai gpt

ELI5 - Simplified Explanation

Imagine there are many different classes in a school and some have to be taken before others. The code begins by creating a large grid to keep track of every possible pair of classes. If class A must happen before class B, the code marks that spot on the grid to show there is a connection.

Sometimes the connections are indirect. For example, if class A leads to class B and class B leads to class C, then class A also leads to class C. The next part of the code goes through every class and looks for these hidden paths. It checks if there is a way to get from one class to another through any intermediate class. If it finds such a path, it marks that connection on the grid too.

Finally, the code looks at the list of questions to ask if one class is a prerequisite for another. Because the grid is now fully updated with all the connections, it just looks at the right spot on the grid for each question to see if the connection exists.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.07 | σ = 1.68

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
muhammadfarhankt SQL
Shamik07 Dart
suxrobGM C#
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
muhammadfarhankt SQL
Shamik07 Dart
suxrobGM C#
wisdompeak C++
withaarzoo C++
27 links | 16 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

7 solutions   March 6, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality