Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in Scala: 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

    SCALA · GRAPHS

    Course Schedule in Scala, explained

    Problem overview

    The method canFinish(numCourses: Int, prerequisites: Array[Array[Int]]): Boolean receives the number of courses and a list of pairs. A pair [a, b] means course b must be taken before course a. The method returns true if all the courses can be taken in some order and false otherwise.

    With numCourses = 2 and [[1, 0]], take course 0, then course 1: true. With [[1, 0], [0, 1]], each course waits for the other, so neither can start: false.

    Approach: take whatever is free

    Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. All the courses can be finished exactly when the arrows contain no cycle, that is, when the courses can be put in a line so that every arrow points forward. Such a line is a topological order.

    Kahn's algorithm builds that line greedily. A course with no prerequisites left can be taken right away. Taking it removes its arrows, and any course that was waiting only for it becomes free. Repeat until nothing is free. If every course got taken, the answer is true. If some are left, each of them waits, directly or not, for a course on a cycle, so the answer is false.

    To make "no prerequisites left" cheap to check, keep for each course a count of its untaken prerequisites, its in-degree, and for each course a list of the courses that wait for it.

    Why does a cycle always block the process? Take any course on a cycle: one of its prerequisites is the previous course on that cycle, which is itself waiting for the course before it, and so on around the loop. None of them ever reaches an in-degree of 0, so none enters the queue. The same goes for any course that depends on one of them, which is why a single cycle anywhere can make the answer false. The other direction holds too: if there is no cycle, there is always at least one course with no untaken prerequisites, so the process never gets stuck before the end.

    Step by step

    1. Create graph: an array of numCourses empty mutable.ArrayBuffer[Int]s. graph(b) will list the courses that wait for course b.
    2. Create inDegree, an array of numCourses zeros. inDegree(a) will count the prerequisites of course a.
    3. Loop over the pairs. For each, append prereq(0) to graph(prereq(1)) and add 1 to inDegree(prereq(0)).
    4. Create a mutable.Queue[Int] and enqueue every course whose inDegree is 0: those can be taken first.
    5. Keep a var taken counter, starting at 0.
    6. While the queue isn't empty, dequeue a course and add 1 to taken. Then go through the courses that wait for it, subtracting 1 from each one's inDegree. When one reaches 0, enqueue it. A count reaches 0 only once, so no course is queued twice.
    7. The last line, taken == numCourses, is the result.

    The solution in Scala

    class Solution {
        def canFinish(numCourses: Int, prerequisites: Array[Array[Int]]): Boolean = {
            val graph = Array.fill(numCourses)(mutable.ArrayBuffer[Int]())
            val inDegree = Array.fill(numCourses)(0)
            for (prereq <- prerequisites) {
                graph(prereq(1)) += prereq(0)
                inDegree(prereq(0)) += 1
            }
            val queue = mutable.Queue[Int]()
            for (course <- 0 until numCourses) {
                if (inDegree(course) == 0) {
                    queue.enqueue(course)
                }
            }
            var taken = 0
            while (queue.nonEmpty) {
                val course = queue.dequeue()
                taken += 1
                for (nextCourse <- graph(course)) {
                    inDegree(nextCourse) -= 1
                    if (inDegree(nextCourse) == 0) {
                        queue.enqueue(nextCourse)
                    }
                }
            }
            taken == numCourses
        }
    }

    The solution uses mutable.ArrayBuffer and mutable.Queue. In a file of your own, add import scala.collection.mutable at the top.

    Scala details

    • Array.fill(numCourses)(mutable.ArrayBuffer[Int]()) evaluates its second argument once per element, so each course gets its own buffer. Putting one buffer in a variable first and filling the array with that variable would make every entry the same buffer: appending 5 to the first entry would show up in the second too.
    • Scala has no ++: counters change with += 1 and -= 1. graph(b) += a on a buffer appends an element.
    • 0 until numCourses excludes the end; 1 to n would include it.
    • A for loop over graph(course) only reads the buffer while the loop runs; nothing here changes it, so iterating is safe.
    • queue.dequeue() throws on an empty queue, which is why the loop checks nonEmpty first.

    Tracing the third example

    For numCourses = 4 and pairs [1, 0], [2, 0], [3, 1], [3, 2], the setup gives:

    graph: [1, 2] [3] [3] []
    inDegree: [0, 1, 1, 2]

    Only course 0 starts in the queue. Taking each course in turn:

    took 0: inDegree=[0, 0, 0, 2] queue=[1, 2]
    took 1: inDegree=[0, 0, 0, 1] queue=[2]
    took 2: inDegree=[0, 0, 0, 0] queue=[3]
    took 3: inDegree=[0, 0, 0, 0] queue=[]

    Four courses were taken, so the method returns true.

    Complexity

    Time is O(V + E) for V courses and E pairs: building the graph visits each pair once, and the queue loop takes each course once and looks at each arrow once. Space is O(V + E) for the buffers, the counts and the queue.

    Edge cases and common mistakes

    • No prerequisites: every course starts in the queue and the answer is true. Both 5 courses and 1 course with an empty list return true.
    • A cycle next to free courses: with 3 courses and pairs [1, 0], [2, 1], [1, 2], course 0 can be taken, but courses 1 and 2 wait for each other. The method returns false, because only 1 of 3 was taken.
    • Swapped direction: the pair [a, b] puts the arrow from b to a. Reversing it everywhere still gives a correct yes or no, but mixing the two directions does not.
    • Returning when the queue starts empty: if no course is free at the start, taken stays 0 and the result is false with no special case.
    • Large inputs: the method is iterative, so a chain of 100000 courses, each needing the previous one, returns true without stack problems. A recursive depth-first search would need care there.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free