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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Similar Problems
- problem 210: Course Schedule II
- problem 261: Graph Valid Tree
- problem 310: Minimum Height Trees
- problem 630: Course Schedule III
- problem 2392: Build a Matrix With Conditions
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- 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