↻one more pass.
Graphs · Medium

Course Schedule: the idea to remember.

Given course prerequisites, decide whether all courses can be completed.

Solve on LeetCode ↗

The core insight

Build edges from each prerequisite to the course requiring it. Repeatedly remove courses whose indegree is zero.

Why it works

A zero indegree course has no remaining prerequisite. If a directed cycle remains, none of its vertices can become available.

The mistake to avoid

Count all courses, including isolated ones, and orient edges consistently.

Time: O(V + E)Space: O(V + E)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

boolean canFinish(int n, int[][] prerequisites) {
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
    int[] degree = new int[n];
    for (int[] pair : prerequisites) { graph.get(pair[1]).add(pair[0]); degree[pair[0]]++; }
    Deque<Integer> queue = new ArrayDeque<>();
    for (int i = 0; i < n; i++) if (degree[i] == 0) queue.add(i);
    int done = 0;
    while (!queue.isEmpty()) {
        int course = queue.remove(); done++;
        for (int next : graph.get(course)) if (--degree[next] == 0) queue.add(next);
    }
    return done == n;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.