Start learning free

LESSON 568 OF 671 · GRAPHS

Course Schedule in Java: 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 18
    Ctrl + Enter to check

    JAVA · GRAPHS

    Course Schedule in Java, explained

    Problem overview

    The method canFinish(int numCourses, int[][] prerequisites) receives the number of courses, labeled 0 to numCourses - 1, 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 finished and false otherwise.

    With numCourses = 2 and prerequisites = [[1, 0]], course 0 needs nothing and course 1 needs course 0, so the order 0, 1 works and the answer is true. With [[1, 0], [0, 1]] each course waits for the other, so neither can ever start and the answer is false.

    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 there is an order of all of them in which every arrow points forward (a topological order). Such an order exists exactly when the arrows contain no cycle.

    Approach: keep taking courses that are free

    A course is free when all of its prerequisites have been taken. Start with the courses that have no prerequisites at all. Taking one removes its outgoing arrows, which may free other courses. Repeat until nothing is free. If every course was taken, the answer is true. If some were left, each of them is waiting for another one that is also left, so there is a cycle, and the answer is false.

    This is Kahn's algorithm. It needs two pieces of data:

    • for every course b, the list of courses that wait for it (graph.get(b));
    • for every course a, its in-degree: the number of prerequisites still not taken, which is the number of arrows pointing into a.

    A queue holds the free courses. Each course enters it at most once, because its count reaches 0 only once, and each pair is looked at once when its first course is taken. That makes the work O(V + E) for V courses and E pairs.

    Step by step

    1. Create graph as a List<List<Integer>> backed by an ArrayList.
    2. Add one empty inner list per course in a loop. Java has no one-line way to make a list of separate lists, so they are added one by one.
    3. Create inDegree, an int array of size numCourses, filled with zeros.
    4. Turn each pair into an arrow. For a pair prereq, add prereq[0] to graph.get(prereq[1]), because course prereq[1] comes first and prereq[0] waits for it. Then add 1 to inDegree[prereq[0]], since it has one more prerequisite.
    5. Create queue as an ArrayDeque declared as Deque<Integer>. add puts a course at the back and poll removes the one at the front, both in constant time.
    6. Seed the queue with every course whose inDegree is 0.
    7. Count the taken courses in taken, starting at 0.
    8. Loop while the queue isn't empty. Poll a course, add 1 to taken, and visit every course in its list.
    9. Release the waiting courses. Subtract 1 from each one's inDegree. If it reaches 0, its last prerequisite was just taken, so add it to the queue.
    10. Return taken == numCourses.

    The solution in Java

    class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            List<List<Integer>> graph = new ArrayList<>();
            for (int i = 0; i < numCourses; i++) {
                graph.add(new ArrayList<>());
            }
            int[] inDegree = new int[numCourses];
            for (int[] prereq : prerequisites) {
                graph.get(prereq[1]).add(prereq[0]);
                inDegree[prereq[0]]++;
            }
            Deque<Integer> queue = new ArrayDeque<>();
            for (int course = 0; course < numCourses; course++) {
                if (inDegree[course] == 0) {
                    queue.add(course);
                }
            }
            int taken = 0;
            while (!queue.isEmpty()) {
                int course = queue.poll();
                taken++;
                for (int nextCourse : graph.get(course)) {
                    inDegree[nextCourse]--;
                    if (inDegree[nextCourse] == 0) {
                        queue.add(nextCourse);
                    }
                }
            }
            return taken == numCourses;
        }
    }
    

    The Java details worth a closer look:

    • Declare with the interface. List and Deque are interfaces and ArrayList and ArrayDeque are the classes behind them. The diamond <> lets the compiler infer the type arguments.
    • Autoboxing. queue.poll() returns an Integer, which is unboxed to an int automatically. The enhanced for over graph.get(course) unboxes each element the same way. poll returns null on an empty queue, but the loop condition guarantees the queue isn't empty, so unboxing never fails here.
    • Arrays start at zero. new int[numCourses] is all zeros, which is the right starting count before the pairs are read.
    • Direction matters. For [a, b] the list belongs to b (prereq[1]) and the counter to a (prereq[0]). Mixing the two up reverses every arrow, and the queue then no longer yields courses in a valid order to take them.
    • Imports. A complete file using these types needs import java.util.*;.

    Complexity

    Time: O(V + E). Building the lists and counts touches every course and every pair once. Each course enters and leaves the queue at most once, and the inner loop runs once per pair across the whole run.

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

    Edge cases and common mistakes

    • No prerequisites. Every count is 0, every course goes into the queue at the start, and taken ends at numCourses. With 3 courses and no pairs the answer is true.
    • A cycle. For [[1, 0], [0, 1]] no course starts with a count of 0, so the queue is empty from the beginning, taken stays 0 and the method returns false.
    • A cycle with free courses around it. With 3 courses and [[1, 0], [2, 1], [1, 2]], course 0 is taken, but courses 1 and 2 wait for each other, so taken is 1 and the answer is false. Courses outside a cycle can be taken; the check against numCourses is what catches the rest.
    • Several prerequisites for one course. Course 3 in [[1, 0], [2, 0], [3, 1], [3, 2]] has an in-degree of 2 and enters the queue only after both 1 and 2 are taken.
    • Returning early. Returning true as soon as the queue first empties, or checking only whether some course starts at 0, misses cycles that don't involve every course.
    • Mixing up the two indices. Using prereq[0] as the key of the list and prereq[1] as the counter builds the graph backwards. Follow the pair's meaning: [a, b] is an arrow from b to a.

    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 = 3, prerequisites = [] gives true.
    • numCourses = 1, prerequisites = [] gives true.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free