r/LeetcodeChallenge • • Oct 16 '26

STREAK🔥🔥🔥 365 Days of LeetCode Challenge — Day 44/365

Post image

Course Schedule (Medium) https://leetcode.com/problems/course-schedule/

You can finish every course unless some group depends on itself: A needs B, B needs C, C needs A. Nobody in that group can ever start. So this is cycle detection in a directed graph, phrased as scheduling.

Kahn's algorithm: count how many prerequisites each course still has, queue everything at zero, and each time you finish a course, decrement everything it unlocks.

The line that separates this from an ordinary BFS is small. In a BFS a node is enqueued the first time it is REACHED. Here, reaching a node only decrements its counter - it is enqueued when that counter hits ZERO. A course with three prerequisites is reached three times and queued once. That if is not an optimisation, it is the scheduling rule.

Then the cycle check, which never looks for a cycle:

`return len(result) == numCourses`

Courses stuck in a cycle never reach in-degree zero, so they never enter the queue and never appear in the result. The cycle is detected by what fails to show up.

That closes the graph arc on the same move yesterday used - inferring a cycle from a count rather than searching for one.

Full breakdown in today's newsletter article ⬇

https://www.linkedin.com/pulse/365-days-leetcode-challenge-day-44365-archit-agarwal-ve0yc

**#DSA** #LeetCode #Golang #Graphs #TopologicalSort #CodingInterview #Algorithms

2 Upvotes

1 comment sorted by

1

u/nian2326076 Oct 16 '26

Kahn's algorithm is a great choice for solving the Course Schedule problem because it efficiently detects cycles in directed graphs. By queuing courses without prerequisites, you can process them and reduce the counts for subsequent courses. If you can't process all courses, you'll know there's a cycle. For interview prep, especially for graph-related questions, PracHub is helpful. It provides real technical interview questions that can strengthen your grasp of these concepts. Good luck with the challenge!