Problem 207

Abstract / Summary

Determine if all courses can be finished given their prerequisites without scheduling conflicts.

Note

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

Python 0207.py

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        needmore = defaultdict(set)
        for p in prerequisites:
            needmore[p[0]].add(p[1])

        resolved = set(range(numCourses)) - needmore.keys()

        again = True
        while again:
            again = False

            remove = set()
            for n in needmore:
                reduce = needmore[n].intersection(resolved)
                if reduce:
                    again = True
                    if len(reduce) == len(needmore[n]):
                        resolved.add(n)
                        remove.add(n)
                    else:
                        needmore[n] -= reduce

            for r in remove:
                del needmore[r]

        return len(needmore) == 0
27 lines | 842 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (5+ million submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Graph Theory
  • 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 determines whether all courses in a curriculum can be completed given a list of prerequisite pairs. It models the prerequisite relationship as a mapping from a course to the set of courses that must be taken before it. By iteratively removing satisfied prerequisites, the algorithm attempts to resolve every course. The final boolean result indicates whether any unresolved dependencies remain.

Key Steps

The construction of the prerequisite map uses a defaultdict of sets, allowing each course to accumulate its required predecessors efficiently.

needmore = defaultdict(set)
for p in prerequisites:
    needmore[p[0]].add(p[1])

A set named resolved is initialized with courses that have no outgoing entries in the map, i.e., courses that are not keys in needmore. These are considered already satisfiable.

resolved = set(range(numCourses)) - needmore.keys()

The core of the algorithm is a loop that continues as long as new courses become resolved during an iteration. The flag again tracks whether any progress was made.

again = True
while again:
    again = False
    ...

Inside the loop, each entry in needmore is examined. The intersection between the current course’s prerequisite set and the resolved set identifies prerequisites that have already been satisfied.

reduce = needmore[n].intersection(resolved)

If any satisfied prerequisites are found, the algorithm marks that progress occurred. When all prerequisites for a course are satisfied (len(reduce) == len(needmore[n])), the course itself is added to resolved and scheduled for removal from needmore. Otherwise, only the satisfied prerequisites are removed from the course’s set.

if reduce:
    again = True
    if len(reduce) == len(needmy[n]):
        resolved.add(n)
        remove.add(n)
    else:
        needmore[n] -= reduce

After processing all entries, the courses collected in remove are deleted from the map, shrinking the problem space for the next iteration.

for r in remove:
    del needmore[r]

When the loop terminates, the algorithm checks whether any entries remain in needmore. An empty map means every course’s prerequisites have been satisfied, and the function returns True; otherwise, it returns False.

return len(needmore) == 0

Edge Cases Handled

When the prerequisites list is empty, the initial construction of needmore yields an empty mapping. Consequently, resolved becomes the full set of courses, and the loop body never executes. The final check confirms that needmore is empty, correctly returning True for a trivially satisfiable curriculum.

If numCourses is zero, the range used to build resolved is empty, and needmore is also empty. The function again returns True, reflecting that there are no courses to schedule.

Courses that appear only as prerequisites but never as a dependent (i.e., they are never keys in needmore) are automatically placed in resolved from the start. This ensures that downstream courses depending on them can be resolved without extra handling.

Cyclic dependencies are naturally detected because none of the courses involved in a cycle can ever have all their prerequisites satisfied. The loop will exhaust all possible reductions without clearing the cyclic entries, leaving needmore non-empty and causing the function to return False.

Performance Optimizations

The use of defaultdict(set) provides constant-time insertion for each prerequisite pair and enables fast membership tests during intersection operations.

Set intersection (needmore[n].intersection(resolved)) quickly isolates satisfied prerequisites without iterating over the entire prerequisite list for each course. This reduces the amount of work per iteration, especially when many prerequisites have already been resolved.

By removing fully satisfied courses from needmore immediately after they are resolved, the algorithm shrinks the size of the dictionary, decreasing the number of entries examined in subsequent iterations. This in-place pruning avoids redundant checks on already satisfied courses.

The again flag prevents unnecessary passes through the outer loop when no progress is made, ensuring that the algorithm terminates as soon as it becomes impossible to resolve additional courses.

Collecting keys to delete in a separate remove set and performing deletions after the inner loop avoids modifying the dictionary while iterating over it, which preserves iteration stability and avoids hidden overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big set of building blocks where some blocks can only be placed after others are already in their spots. Think of this like needing to put on your socks before your shoes.

The code starts by looking at all the rules for which blocks must come first. It keeps a list of tasks that are ready to go because they have no waiting left to do.

Then the code enters a loop to play a game of check and clear. It looks at all the tasks that are still waiting for other pieces to be finished. If it finds a task that has finally had all of its required pieces put in place, that task is marked as finished and moved to the ready pile. This makes it easier for the next blocked task to move forward.

The process repeats over and over again, clearing away the waiting list bit by bit. Sometimes things continue to move along smoothly, but if it gets stuck and nothing new can be finished, the loop stops. At the end, the code checks to see if every single task was successfully finished or if some are still stuck waiting forever.

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 = 6 | μ = 6.26 | σ = 1.53

Complexity Analysis

not analyzed yet

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 C# Rust TS Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong TS
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong TypeScript
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
57 links | 41 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Course Schedule | Apple | Microsoft | Amazon | BFS | Graph Concepts & Qns - 12 | Leetcode 207'
codestorywithMIK 15 mins
Course Schedule | Apple | Microsoft | Amazon | BFS | Graph Concepts & Qns - 12 | Leetcode 207
YouTube video 'Course Schedule (Detecting Cycles in a Graph) - Leetcode 207 - Graphs (Python)'
Greg Hogg 14 mins
Course Schedule (Detecting Cycles in a Graph) - Leetcode 207 - Graphs (Python)
YouTube video 'Course Schedule | LeetCode 207 | Cycle in Directed Graph | C++, Java, Python'
Knowledge Center 30 mins
Course Schedule | LeetCode 207 | Cycle in Directed Graph | C++, Java, Python
YouTube video 'Course Schedule | Apple | Microsoft | Amazon | DFS | Graph Concepts & Qns - 14 | Leetcode 207'
codestorywithMIK 13 mins
Course Schedule | Apple | Microsoft | Amazon | DFS | Graph Concepts & Qns - 14 | Leetcode 207
YouTube video 'LeetCode 207 & 210: Course Schedule I & II | Topological Sort | Kahn's algorithm - Interview Ep 78'
Fisher Coder 24 mins
LeetCode 207 & 210: Course Schedule I & II | Topological Sort | Kahn's algorithm - Interview Ep 78
YouTube video 'Course Schedule - LeetCode #207 with python programming'
CodingNinja 15 mins
Course Schedule - LeetCode #207 with python programming
YouTube video 'Leetcode 207 - Course Schedule (JAVA, Solution Explain!)'
LC Bear 24 mins
Leetcode 207 - Course Schedule (JAVA, Solution Explain!)
YouTube video 'COURSE SCHEDULE | LEETCODE # 207 | PYTHON TOPOLOGICAL SORT SOLUTION'
Cracking FAANG 17 mins
COURSE SCHEDULE | LEETCODE # 207 | PYTHON TOPOLOGICAL SORT SOLUTION
YouTube video 'LeetCode 207 | Course Schedule'
leetuition 20 mins
LeetCode 207 | Course Schedule
YouTube video 'Course Schedule | Topological Sort | Cycle in Directed Graph | Leetcode 207'
Aryan Mittal 12 mins
Course Schedule | Topological Sort | Cycle in Directed Graph | Leetcode 207
YouTube video 'Course Schedule- LeetCode 207 - Python #leetcode #graph'
Deepti Talesra 18 mins
Course Schedule- LeetCode 207 - Python #leetcode #graph
YouTube video 'Course Schedule - DFS - LeetCode 207 - Google Coding Interview Question'
AlgoJS 7 mins
Course Schedule - DFS - LeetCode 207 - Google Coding Interview Question
YouTube video 'Course Schedule | Day 29 | [May LeetCoding Challenge] [Leetcode 207] [2020]'
Algorithms Made Easy 6 mins
Course Schedule | Day 29 | [May LeetCoding Challenge] [Leetcode 207] [2020]
YouTube video 'LeetCode 207. Course Schedule I - (Kahn's Algorithm / BFS)'
Kacy Codes 10 mins
LeetCode 207. Course Schedule I - (Kahn's Algorithm / BFS)
YouTube video 'Leetcode 207: Course Schedule'
Algorithms Casts 36 mins
Leetcode 207: Course Schedule
YouTube video '207. Course Schedule (LeetCode, Java)'
hakunamatasq 9 mins
207. Course Schedule (LeetCode, Java)
YouTube video '207. Course Schedule (updated link in description) (Leetcode Medium)'
Programming Live with Larry 26 mins
207. Course Schedule (updated link in description) (Leetcode Medium)
YouTube video 'LeetCode 207 | Course Schedule | BFS HashMap, List[] | Java'
Sleepy Cracker 9 mins
LeetCode 207 | Course Schedule | BFS HashMap, List[] | Java
YouTube video '207 || Course Schedule || C++ || Leetcode Daily Challenge'
CodeFreaks 13 mins
207 || Course Schedule || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #1199: Jul 13, 2023 - 207. Course Schedule'
Programming Live with Larry 14 mins
Daily Leetcode #1199: Jul 13, 2023 - 207. Course Schedule
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

25 solutions   September 4, 2023

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