LC 207: Course Schedule
Detecting cycles in a directed graph using topological sort (BFS/Kahn's algorithm):: ON THIS PAGE 3
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 $b_i$ first if you want to take course $a_i$.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Intuition
This is a graph problem, essentially we need to detect if there is a cycle. We can achieve this with topological sort using kahn's algorithm
Approach
# Track how many prerequisites each course has (in-degree)
= *
# Map each course to the list of courses that depend on it
# course_map[A] = [B, C] means "after taking A, you can take B and C"
=
# Build the graph
+= 1 # This course has one more prerequisite
# pre -> course
# Counter for how many courses we can successfully take
= 0
# Start with courses that have no prerequisites (in-degree = 0)
# These are our entry points - we can take them immediately
=
# If no courses have 0 prerequisites, there's a cycle (every course depends on something)
return False
# Process courses using topological sort (Kahn's algorithm)
=
+= 1
# For each course that depends on the one we just took
-= 1 # Remove this prerequisite requirement
# If this course now has all prerequisites met, we can take it
# If we took all courses, there's no cycle. Otherwise, there's a cycle.
return ==
Complexity
- Time: $O(V + E)$
- Space: $O(V + E)$
> finding connected notes…
> 4 notes share a tag
210-course-schedule-2.md LC 210: Course Schedule II 295-median-from-data-stream.md LC 295: Find Median from Data Stream 443-string-compression.md LC 443: String Compression 01-two-sum.md LC 001: Two Sum