Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in Kotlin: Topological Sort with Kahn's Algorithm

Practice O(V + E) Read the full explanation

You get numCourses courses, numbered 0 to numCourses - 1. You also get an array prerequisites of pairs [a, b]. A pair means you must finish course b before you start course a.

Return true if you can take all the courses in some order. If you can't, return false.

 

Example 1:

Input: numCourses = 5, prerequisites = [[1, 0], [2, 1], [4, 3], [4, 2]]
Output: true
Explanation: Each arrow goes from a course to a course that needs it:
    0 → 1 → 2 → 4
            3 → 4
Course 4 needs both 2 and 3.
Taking the courses in number order, from 0 to 4, works.

Example 2:

Input: numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 2], [1, 3]]
Output: false
Explanation: The arrows 1 → 2 → 3 → 1 form a loop.
Course 1 waits for course 3.
Course 3 waits for course 2.
Course 2 waits for course 1.
Course 0 is fine, but the other three can never start.

Example 3:

Input: numCourses = 3, prerequisites = []
Output: true
Explanation: No course has a prerequisite, so any order works.

 

Constraints:

  • 1 to 100,000 courses.
  • Up to 100,000 pairs.
  • Both courses in a pair are valid course numbers.
  • The two courses in a pair are different.
  • No pair appears twice.
STEP 1 OF 16
    Ctrl + Enter to check

    KOTLIN · GRAPHS

    Course Schedule in Kotlin, explained

    Problem overview

    The function canFinish receives numCourses and an Array<IntArray> named prerequisites. A pair [a, b] means course b must be taken before course a. The function returns true if every course can be taken in some order that respects all the pairs, and false otherwise.

    With numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], course 0 needs nothing, courses 1 and 2 need course 0, and course 3 needs both 1 and 2. The order 0, 1, 2, 3 works, so the answer is true. With [[1, 0], [0, 1]] each of the two courses waits for the other, so neither can ever be taken and the answer is false.

    Approach: take free courses first

    Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. An order of all the courses in which every arrow points forward is a topological order. All courses can be finished exactly when such an order exists, which happens exactly when the arrows contain no cycle.

    Kahn's algorithm builds the order greedily:

    1. Count, for each course, how many prerequisites it still waits for. This count is its in-degree, the number of arrows pointing into it.
    2. Put every course whose count is 0 into a queue. These can be taken right now.
    3. Take a course from the queue. Each course that waits for it now has one prerequisite fewer. If a count drops to 0, that course joins the queue.
    4. Repeat until the queue is empty, and count how many courses were taken.

    Courses on a cycle wait for each other, so their counts never reach 0 and they are never taken. The same holds for any course that needs one of them. So the answer is whether the number of courses taken equals numCourses.

    The work is O(V + E) for V courses and E pairs, which matters because both can reach 100,000. A recursive depth-first search for cycles is another option, but the queue-based version has no recursion to overflow.

    Step by step

    1. Build graph. Array(numCourses) { mutableListOf<Int>() } creates one empty mutable list per course. graph[b] will hold the courses that wait for course b.
    2. Create inDegree, an IntArray of zeros. inDegree[a] counts the prerequisites of course a that haven't been taken.
    3. Loop over prerequisites. For each pair, add prereq[0] to graph[prereq[1]] and increase inDegree[prereq[0]] by one.
    4. Create the queue, an ArrayDeque<Int>. Adding at the back and removing from the front are both O(1).
    5. Seed the queue. Loop over 0 until numCourses and add each course with inDegree[course] == 0. If there are none, every course waits for another, and nothing can start.
    6. Declare taken as a var at 0. It counts the courses taken.
    7. Run the queue. While it isn't empty, remove the front course, increase taken, and loop over graph[course].
    8. Update each waiting course. Decrease inDegree[nextCourse]. If it reaches 0, add nextCourse to the queue. A count reaches 0 only once, so each course enters the queue at most once.
    9. Return taken == numCourses.

    The solution in Kotlin

    class Solution {
        fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
            val graph = Array(numCourses) { mutableListOf<Int>() }
            val inDegree = IntArray(numCourses)
            for (prereq in prerequisites) {
                graph[prereq[1]].add(prereq[0])
                inDegree[prereq[0]]++
            }
            val queue = ArrayDeque<Int>()
            for (course in 0 until numCourses) {
                if (inDegree[course] == 0) {
                    queue.add(course)
                }
            }
            var taken = 0
            while (queue.isNotEmpty()) {
                val course = queue.removeFirst()
                taken++
                for (nextCourse in graph[course]) {
                    inDegree[nextCourse]--
                    if (inDegree[nextCourse] == 0) {
                        queue.add(nextCourse)
                    }
                }
            }
            return taken == numCourses
        }
    }
    

    On the third example, the tables right after the loop over prerequisites, and then the state after each course is taken, look like this:

    graph=[[1, 2], [3], [3], []]  inDegree=[0, 1, 1, 2]
    take 0  inDegree=[0, 0, 0, 2]
    take 1  inDegree=[0, 0, 0, 1]
    take 2  inDegree=[0, 0, 0, 0]
    take 3  inDegree=[0, 0, 0, 0]
    

    Course 3 enters the queue only when its count reaches 0, after both 1 and 2 have been taken. All four courses are taken, so the function returns true.

    The Kotlin details worth knowing:

    • One list per course. The block in Array(numCourses) { ... } runs once per index, so each slot gets its own MutableList. Filling the array with one shared list would mix all the courses together.
    • kotlin.collections.ArrayDeque. ArrayDeque is available in Kotlin without any import. It offers add, removeFirst and isNotEmpty. Calling removeFirst on an empty deque throws, which is why the loop checks isNotEmpty() first.
    • inDegree[prereq[0]]++ changes an element of an IntArray in place. The array reference is a val, but its elements are mutable.
    • Modifying while iterating. The inner for reads graph[course] and only changes inDegree and queue, never the list being walked, so it is safe.

    Complexity

    Time: O(V + E). Building the graph touches each pair once. Seeding the queue looks at each course once. Each course is removed from the queue at most once, and its list is walked once, so over the whole run every pair is examined once.

    Space: O(V + E). The adjacency lists hold one entry per pair, and inDegree, the queue and the array of lists hold at most one entry per course.

    Edge cases and common mistakes

    • No prerequisites. Every count is 0, every course goes into the queue, and the result is true. This is true for numCourses = 3 and an empty array.
    • Reversed arrows. In [a, b], b comes first. The solution stores a in graph[b] and counts the in-degree of a. Mixing the two up reverses every arrow, and the counts then no longer match the steps of the lesson.
    • A cycle hiding behind free courses. With numCourses = 3 and [[1, 0], [2, 1], [1, 2]], course 0 is free, but courses 1 and 2 wait for each other. Only course 0 is taken, and the result is false.
    • Returning true when the queue starts non-empty. Some free courses don't prove the schedule works. Only the final count of taken courses does.

    Testing

    • numCourses = 2, prerequisites = [[1, 0]] gives true.
    • numCourses = 2, prerequisites = [[1, 0], [0, 1]] gives false.
    • numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] gives true.
    • numCourses = 3, prerequisites = [[1, 0], [2, 1], [1, 2]] gives false.
    • numCourses = 1, prerequisites = [] gives true.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free