Course Schedule Problem Using Graph Topological Sort - Visualization

Problem Statement

You are given n tasks labeled from 0 to n - 1 and an array of prerequisite pairs. Each pair [a, b] indicates that task b must be completed before task a.

Return any valid order in which the tasks can be completed. If no such order exists (due to a cycle), return an empty array.

Examples

n Prerequisites Valid Output Description
2 [[1, 0]] [0, 1] Task 1 depends on 0, so 0 must come first
4 [[1, 0], [2, 0], [3, 1], [3, 2]] [0, 1, 2, 3] Task 3 depends on both 1 and 2, which in turn depend on 0
1 [] [0] Single task with no prerequisites
3 [[0, 1], [1, 2], [2, 0]] [] Cycle detected, impossible to complete all tasks
5 [] [0, 1, 2, 3, 4] No dependencies, any order is valid

Solution

Understanding the Problem

We are given a number of courses, and a list of prerequisite pairs. Each pair [a, b] means you must complete course b before course a. Our task is to determine if it’s possible to finish all courses, and if yes, return one possible order in which to take them.

This is a classic problem of dependency resolution and can be modeled as a directed graph where each course is a node, and each prerequisite is a directed edge. If the graph contains a cycle, then it is impossible to finish all courses. Otherwise, we can generate a valid course order using topological sorting.

Step-by-Step Solution with Example

Step 1: Represent the Problem as a Graph

We treat each course as a node. If course b is a prerequisite for course a, we draw a directed edge from b to a.

Example:
Let’s say numCourses = 4 and prerequisites = [[1,0],[2,0],[3,1],[3,2]].
This means:
- Take course 0 before 1
- Take course 0 before 2
- Take course 1 before 3
- Take course 2 before 3
So, the graph looks like:

0 → 1 → 3
        ↑
  → 2 ———┘

Step 2: Initialize In-Degree Array and Adjacency List

The in-degree of a node is the number of prerequisites it has. We create:

  • An adjacency list to store which courses depend on each course.
  • An in-degree array to count prerequisites for each course.

Step 3: Enqueue Courses with In-Degree 0

Courses with no prerequisites (in-degree 0) can be taken immediately. We add them to a queue.

In our example, only course 0 has in-degree 0 initially, so we enqueue it.

Step 4: Process the Queue

While the queue is not empty:

  • Remove a course from the queue and add it to the result list.
  • For each course that depends on it, reduce its in-degree by 1.
  • If any course’s in-degree becomes 0, enqueue it.

For our example:

  1. Start with [0]
  2. Process 0 → add [1, 2] to queue → result: [0]
  3. Process 1 → reduce in-degree of 3 → result: [0, 1]
  4. Process 2 → reduce in-degree of 3 → result: [0, 1, 2]
  5. Now 3 has in-degree 0 → enqueue → result: [0, 1, 2, 3]

Step 5: Check if All Courses Are Taken

If the result list contains all courses, we return it. If not, it means there’s a cycle and we return an empty array.

Edge Cases

  • Cycle in prerequisites: Example: [[1,0],[0,1]]. This creates a loop: 0 → 1 → 0. It’s impossible to finish all courses.
  • No prerequisites: All courses are independent. Any order is valid.
  • Single course: Always possible to finish it.
  • Multiple valid orders: For acyclic graphs, many topological sorts are possible.

Finally

This problem teaches us how to model real-world scheduling problems using graphs. Topological sorting is the key idea, and cycle detection helps us rule out impossible scenarios. By translating the prerequisites into a graph and using in-degree tracking, we can determine if all tasks (courses) can be completed, and in what order.

Algorithm Steps

  1. Create an adjacency list for the graph.
  2. Create an array to track in-degree for each task.
  3. Populate the adjacency list and in-degree array based on prerequisites.
  4. Initialize a queue with all tasks having in-degree 0.
  5. While the queue is not empty:
    1. Remove a task from the queue and add it to the result list.
    2. For each neighbor of that task, reduce its in-degree by 1.
    3. If any neighbor’s in-degree becomes 0, add it to the queue.
  6. After processing, if the result contains all tasks, return it.
  7. Otherwise, return an empty array (cycle detected).

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>

#define MAX 1000

int adj[MAX][MAX], inDegree[MAX], queue[MAX];
int front = 0, rear = -1;

void findOrder(int n, int prerequisites[][2], int m) {
    for (int i = 0; i < m; i++) {
        int a = prerequisites[i][0];
        int b = prerequisites[i][1];
        adj[b][a] = 1;
        inDegree[a]++;
    }

    for (int i = 0; i < n; i++) {
        if (inDegree[i] == 0) queue[++rear] = i;
    }

    int result[MAX], idx = 0;
    while (front <= rear) {
        int node = queue[front++];
        result[idx++] = node;
        for (int i = 0; i < n; i++) {
            if (adj[node][i]) {
                inDegree[i]--;
                if (inDegree[i] == 0) queue[++rear] = i;
            }
        }
    }

    if (idx != n) printf("[]\n");
    else {
        printf("[ ");
        for (int i = 0; i < idx; i++) printf("%d ", result[i]);
        printf("]\n");
    }
}

int main() {
    int prerequisites1[][2] = {{1, 0}};
    findOrder(2, prerequisites1, 1);

    int prerequisites2[][2] = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};
    findOrder(4, prerequisites2, 4);
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(V + E)In all cases, we must visit every node and edge to build the graph and perform topological sorting.
Average CaseO(V + E)Each course and each prerequisite relation must be examined exactly once.
Worst CaseO(V + E)Even with complex dependencies, we still process every node and edge once for sorting and cycle detection.

Space Complexity

O(V + E)

Explanation: We use an adjacency list (O(E)) and an in-degree array and queue (O(V)) to store and process the graph.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...