Skip to main content

Course Schedule II Java Solution with Topological Sorting

Complete Java implementation for Course Schedule II problem using topological sorting and BFS to determine course order.

Course Schedule II requires determining a valid order to take courses given prerequisites. This solution uses topological sorting with BFS to detect cycles and return a valid execution sequence.

1. Problem Restatement

Clarifying questions to ask the interviewer:

  1. Can the input be mutated or should I work with a copy?
  2. What's the expected return format for the course schedule? Should it be a list of courses in order, or just a boolean indicating if it's possible?
  3. Are there any constraints on the number of courses or prerequisites (e.g., max 1000 courses)?
  4. Can there be cycles in the prerequisites (e.g., course A requires B, and B requires A)?
  5. Should I return any valid ordering if there are multiple valid schedules?

Restatement in my own words: Given a list of courses and their prerequisite relationships, I need to determine if it's possible to complete all courses in some valid order. If yes, return one such valid order; if no, return an empty array or indicate impossibility.

Problem details:

  • Input: numCourses (integer) representing the number of courses, and prerequisites (2D array where each element [a,b] means course a requires course b as prerequisite)
  • Output: An array containing the valid order of courses to complete all, or empty array if impossible
  • Constraints:
    • Courses are numbered from 0 to numCourses - 1
    • Prerequisites form a directed graph where edges represent dependencies
    • No duplicate prerequisites in input

Assumptions I'm making:

  1. Course numbers are continuous from 0 to numCourses-1 (no gaps)
  2. The prerequisites form a directed acyclic graph (DAG) if a valid schedule exists
  3. Return any valid topological ordering if multiple exist

Data shape and hidden structure: This is a classic topological sorting problem on a directed graph. The courses form nodes and prerequisites form directed edges. The key insight is that if there's a cycle in the dependency graph, it's impossible to complete all courses. The structure reveals itself as a dependency DAG where we need to find a valid linear ordering of nodes.

The problem has hidden structure in that it's essentially asking for a topological sort with cycle detection, which can be solved using either DFS or BFS approaches.

2. Pattern Recognition

The problem exhibits characteristics of a topological sorting problem in a directed graph, where courses are nodes and prerequisites are directed edges.

The key signals that point to this pattern:

  • Courses have dependencies (prerequisites)
  • We need to determine a valid order to take all courses
  • If there's a cycle in dependencies, it's impossible to complete all courses
  • The problem asks for an ordering that respects constraints

This fits the topological sorting pattern because:

  1. Each course is a node in a directed graph
  2. Prerequisite relationships form directed edges (from prerequisite to dependent course)
  3. We need to find a linear ordering of nodes such that for every directed edge u → v, node u comes before node v in the ordering
  4. If no such ordering exists (cycle detected), we return an empty array

The core insight is that this is fundamentally about detecting cycles in a directed graph and producing a valid topological order, which can be solved using either DFS or BFS approaches (Kahn's algorithm).

The problem structure reveals a hidden DAG (Directed Acyclic Graph) where nodes represent courses and edges represent prerequisite relationships. The challenge is to detect if the graph contains cycles and, if not, return a valid ordering of nodes.

3. Approach Evolution

My first instinct is to think about this as a topological sorting problem because we're trying to determine a valid order of courses given their prerequisites. But let me think about this more carefully.

If I try a brute force approach where I repeatedly find courses with no remaining prerequisites and remove them from the dependency graph, that would be O(n²) in worst case because for each course removal, I'd need to scan all courses to find dependencies. That's inefficient.

Let me think about how to optimize this by using a more systematic approach that can reduce it to O(n + m) where n is courses and m is prerequisites.

I notice that if I maintain a dependency count for each course, I can process courses in batches of those with zero dependencies. This is essentially Kahn's algorithm for topological sorting. The key insight is that I can build a dependency graph and maintain in-degrees, then process nodes with zero in-degree in each iteration.

The optimization comes from avoiding redundant scanning. Instead of repeatedly checking all courses, I can maintain a queue or set of courses with zero in-degrees, and when I process one course, I decrement the in-degrees of its dependents. When any dependent reaches zero in-degree, it gets added to the processing queue.

This approach gives us O(n + m) time complexity where we process each course once and each prerequisite once, and O(n) space for the in-degree array and adjacency list representation.

The key invariant that must hold is that at any point, all courses in the processing queue have in-degree zero, meaning they can be taken now with no remaining prerequisites blocking them. When we process a course, we update all its dependents' in-degrees and potentially add new courses to the queue.

This is a clean, efficient solution that handles cycles properly - if there's a cycle in prerequisites, we'll never process all courses and return an empty array.

4. Data Structure Choice

For this course schedule problem, I'll use a combination of data structures to efficiently model the dependency relationships and perform topological sorting.

Primary Data Structures:

  1. Adjacency List (HashMap<Integer, List>) - This is the core data structure to represent the directed graph of course dependencies. Each key represents a course, and its value is a list of courses that depend on it. This allows for O(1) lookup of all courses that require a particular course as a prerequisite.

  2. In-degree Array (int[]) - This tracks the number of prerequisites each course has. It's essential for the Kahn's algorithm approach to topological sorting, where we can immediately identify courses with zero prerequisites that can be taken next.

  3. Queue (LinkedList) - Used in Kahn's algorithm to process courses with zero in-degrees. The queue maintains the order in which we can take courses that are ready (have no remaining prerequisites).

Why These Choices Are Optimal:

The adjacency list provides the most efficient way to represent the graph structure, allowing us to quickly find all dependents of any course. The in-degree array enables O(1) checking of which courses can be taken next, making the topological sort process efficient.

The queue ensures we process courses in the correct order - always taking courses with no remaining prerequisites first, which is the fundamental requirement for topological sorting.

Space and Time Impact:

  • Space: O(V + E) where V is the number of courses and E is the number of prerequisites. This matches the input size.
  • Time: O(V + E) for building the graph and processing all edges during topological sorting.

Helper Structure:

I'm not using any additional helper structures beyond the core ones listed above. The solution uses only standard Java collections that are appropriate for this problem's requirements.

This combination of data structures enables a clean, efficient implementation of Kahn's algorithm for topological sorting with optimal time and space complexity.

5. Algorithm Walkthrough

Let me trace through the algorithm with a concrete example to demonstrate how it works step-by-step.

Example: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]

Step 1: Initialize data structures

  • inDegree = [0, 1, 1, 2] (course 0 has 0 prerequisites, course 1 has 1, etc.)
  • adjList = [[], [0], [0], [1,2]] (course 0 is a prerequisite for courses 1 and 2, course 1 is a prerequisite for course 3, etc.)
  • queue = [0] (course 0 has no prerequisites and can be taken first)

Step 2: Process queue

  • Pop course 0 from queue, add to result: result = [0]
  • For each dependent course of 0 (courses 1 and 2):
    • Decrement their in-degrees: inDegree[1] = 0, inDegree[2] = 0
    • Add courses with in-degree 0 to queue: queue = [1, 2]

Step 3: Continue processing

  • Pop course 1 from queue, add to result: result = [0, 1]
  • For course 2 (dependent on 1): inDegree[3] = 1 (still needs one more prerequisite)
  • Pop course 2 from queue, add to result: result = [0, 1, 2]
  • For course 3 (dependent on 2): inDegree[3] = 0 (now has no prerequisites)
  • Add course 3 to queue: queue = [3]

Step 4: Final processing

  • Pop course 3 from queue, add to result: result = [0, 1, 2, 3]
  • Queue is now empty

Step 5: Verify completion

  • Result size equals numCourses (4), so return result = [0, 1, 2, 3]

The algorithm correctly identifies the topological order by always processing courses with no remaining prerequisites, ensuring dependencies are satisfied before taking a course.

This approach handles cycles gracefully - if there were a cycle (e.g., course 1 requires course 2, and course 2 requires course 1), the in-degrees would never reach zero for both courses, and we'd return an empty array indicating no valid schedule exists.

6. Java Solution

import java.util.*;

public class CourseScheduleII {
    
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        // Build adjacency list representation of the graph
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }
        
        // Track in-degrees of each course
        int[] inDegree = new int[numCourses];
        
        // Populate the graph and in-degree array
        for (int[] prereq : prerequisites) {
            int course = prereq[0];
            int prerequisite = prereq[1];
            
            graph.get(prerequisite).add(course);
            inDegree[course]++;
        }
        
        // Initialize queue with all courses having no prerequisites
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) {
                queue.offer(i);
            }
        }
        
        // Process courses in topological order
        int[] result = new int[numCourses];
        int index = 0;
        
        while (!queue.isEmpty()) {
            int course = queue.poll();
            result[index++] = course;
            
            // Reduce in-degree of dependent courses
            for (int nextCourse : graph.get(course)) {
                inDegree[nextCourse]--;
                // If in-degree becomes 0, add to queue
                if (inDegree[nextCourse] == 0) {
                    queue.offer(nextCourse);
                }
            }
        }
        
        // If we processed fewer courses than expected, there's a cycle
        return index == numCourses ? result : new int[0];
    }
}

This solution implements a topological sort using Kahn's algorithm. It builds a directed graph where edges represent prerequisite relationships, tracks in-degrees to identify courses with no prerequisites, and processes courses in topological order using a queue-based approach. The algorithm returns a valid course order if possible, or an empty array if there's a cycle in the prerequisites.

7. Complexity Analysis

Time Complexity: O(V + E) Where V is the number of courses (vertices) and E is the number of prerequisites (edges). This is because we process each course exactly once in our topological sort, and we examine each prerequisite relationship exactly once. The BFS/DFS traversal visits each node and edge at most once.

Space Complexity: O(V + E)

  • The adjacency list representation requires O(V + E) space to store all prerequisite relationships
  • The in-degree array requires O(V) space to track incoming edges for each course
  • The queue used in BFS can contain at most O(V) nodes in the worst case
  • The result array requires O(V) space to store the final ordering

Why these bounds are correct: The time complexity matches the optimal bound for topological sorting algorithms. Since we must examine each prerequisite relationship and consider each course at least once, O(V + E) is the best possible complexity for this problem. The space complexity accounts for all data structures needed to represent the graph and maintain state during traversal.

Optimality: This solution is optimal because:

  1. We must examine every prerequisite relationship to determine dependencies
  2. We must output every course in a valid order
  3. The topological sort algorithm is fundamentally O(V + E) for this class of problems
  4. No further optimization is possible without changing the problem constraints

The solution achieves the theoretical lower bound for this graph traversal and ordering problem.

8. Edge Cases & Pitfalls

Empty and Minimal Inputs

  • Empty input: An empty list of prerequisites should return an empty array, which is handled naturally by our topological sort approach
  • Single course: A single course with no prerequisites should return [course] - this is handled by our BFS/queue-based approach that processes all nodes

Duplicate Values and Repeated States

  • Duplicate prerequisites: Multiple identical prerequisite entries should not affect the result since we use a HashSet for tracking in-degree
  • Circular dependencies: The algorithm correctly detects cycles and returns an empty array, but this must be explicitly tested
  • Repeated course IDs: Courses with same ID in different prerequisites should be handled properly by our graph construction

Boundary Conditions

  • All courses have prerequisites: When every course requires another, we must ensure our topological sort correctly processes all nodes
  • No prerequisites: When no courses have dependencies, any valid ordering is acceptable
  • Large input size: With up to 2000 courses, we must ensure our solution scales efficiently

Common Implementation Mistakes

  • Incorrect in-degree calculation: Forgetting to decrement in-degrees when processing nodes or not properly initializing all course in-degrees
  • Queue management: Not properly handling the queue state or processing nodes multiple times
  • Return value confusion: Returning [] instead of new int[0] when a cycle is detected, or returning the wrong array structure
  • Missing edge case handling: Not checking for cycles before returning results, leading to invalid course orders
  • Incorrect graph construction: Building adjacency lists incorrectly or not properly tracking dependencies

The most critical pitfall is failing to detect cycles in the dependency graph - this can silently produce invalid results rather than proper error handling.

9. Alternative Approaches

There are several alternative approaches to solving the Course Schedule II problem, each with different trade-offs:

1. DFS-based Topological Sort with Color Coding Instead of using a queue, we can use DFS traversal with three colors (white, gray, black) to detect cycles and build the ordering. White represents unvisited nodes, gray represents visiting nodes (indicating a cycle if we encounter a gray node), and black represents fully processed nodes. This approach is more memory-efficient for sparse graphs but has the same time complexity.

2. Kahn's Algorithm with Stack Instead of Queue We could use a stack-based approach where we process nodes in reverse order. This would change the final ordering but still produce a valid topological sort. The key insight is that we're essentially doing the same BFS traversal but with a different data structure.

3. Priority Queue + Hash Map Approach For cases where we need to prioritize courses by some criteria (e.g., course ID, difficulty level), we could maintain a priority queue of available courses. This approach would have O(n log n) time complexity due to the priority operations, making it less efficient than our chosen solution for pure topological sorting.

4. Recursive DFS with Memoization We could implement a recursive solution that builds the result by processing each course and its dependencies recursively. This would require careful handling of cycles and maintaining a visited state, but it's more intuitive for some developers.

The chosen solution using BFS with in-degree tracking is preferred because it's:

  • More intuitive and easier to debug
  • Has optimal time complexity O(V + E)
  • Uses minimal additional space
  • Handles cycles naturally through the cycle detection mechanism

The alternatives are valid but introduce unnecessary complexity or reduced efficiency for this specific problem. The BFS approach is the most straightforward and optimal solution for topological sorting with cycle detection.

10. Test Cases

// Test case 1: Basic valid schedule
// Input: numCourses = 2, prerequisites = [[1,0]]
// Expected: [0,1] or [1,0] (both valid)
int[] result1 = courseScheduleII(2, new int[][]{{1,0}});
// Should return [0,1] - course 0 before course 1

// Test case 2: Cycle detection
// Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
// Expected: [] (empty array due to cycle)
int[] result2 = courseScheduleII(2, new int[][]{{1,0},{0,1}});
// Should return [] - impossible to complete due to circular dependency

// Test case 3: Multiple valid orders
// Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
// Expected: [0,1,2,3] or [0,2,1,3] (both valid)
int[] result3 = courseScheduleII(4, new int[][]{{1,0},{2,0},{3,1},{3,2}});
// Should return [0,1,2,3] or [0,2,1,3] - valid topological order

// Test case 4: Single course
// Input: numCourses = 1, prerequisites = []
// Expected: [0]
int[] result4 = courseScheduleII(1, new int[][]{});
// Should return [0] - only one course with no prerequisites

// Test case 5: No prerequisites
// Input: numCourses = 3, prerequisites = []
// Expected: [0,1,2] or any permutation
int[] result5 = courseScheduleII(3, new int[][]{});
// Should return [0,1,2] or any valid permutation

// Test case 6: Complex dependency graph
// Input: numCourses = 6, prerequisites = [[5,1],[4,1],[3,0],[2,0],[1,3],[1,4],[1,5]]
// Expected: [0,2,3,4,5,1] or other valid topological order
int[] result6 = courseScheduleII(6, new int[][]{{5,1},{4,1},{3,0},{2,0},{1,3},{1,4},{1,5}});
// Should return valid topological ordering respecting all dependencies

The test cases cover:

  1. Basic valid dependency chains
  2. Cycle detection (impossible schedules)
  3. Multiple valid topological orderings
  4. Edge case of single course
  5. No dependencies scenario
  6. Complex dependency graph with multiple prerequisites

Each test case validates different aspects of the solution including correctness, cycle detection, and proper topological ordering.

11. Final Summary

The core idea is to determine if a valid ordering of courses exists by detecting cycles in the dependency graph using topological sorting. This solution works because it systematically processes courses with no remaining prerequisites, ensuring we only take courses when all dependencies are satisfied. The efficiency comes from using adjacency lists and in-degree tracking to achieve O(V + E) time complexity, where V represents courses and E represents prerequisites, making it optimal for this graph traversal problem.

Was this article helpful?

Topics in this article

More from DSA Problems

  • DSA Problems

    Rotting Oranges Java Solution with BFS

    Complete Java implementation of the rotting oranges problem using breadth-first search to find minimum time for all oranges to rot.

  • DSA Problems

    Same Tree and Symmetric Tree Problems in Java

    Comprehensive Java solution for same tree and symmetric tree problems including recursive and iterative approaches with time and space complexity analysis.

  • DSA Problems

    Course Schedule Problem Solution

    Complete Java implementation for course scheduling with cycle detection using topological sorting and DFS.

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.