Course Schedule I

Topological Sort DSA practice problem on Onlearn.

Difficulty: hard.

Topics: Determining if all tasks with prerequisites can be completed and finding a valid task execution order (Course Schedule/Prerequisite Tasks Problem), Graph, Directed Graph, Adjacency List, Graph Traversal, Breadth-First Search, Queue, Topological Sorting, Directed Acyclic Graph, Cycle Detection, Time Complexity, Space Complexity, graph representation, topological sort, graph properties, cycle detection, bfs, Graph Representation, Cycle Detection in Directed Graphs.

Problem Statement There are a total of n tasks you have to pick, labeled from 0 to n 1. Some tasks may have prerequisites. For example, if task A depends on task B, it means you must finish task B before you can pick task A. This dependency is expressed as a pair [A, B] (meaning task A requires task B). Given the total number of n tasks and a list of m prerequisite pairs, your task is to find one order of tasks you should pick to finish all tasks. If it is impossible to finish all tasks due to a cyclic dependency, return an empty array. Input Specification The first line contains two integers n and m, representing the total number of tasks and the number of prerequisite pairs, respectively. The next m lines each contain two integers u and v, representing a prerequisite pair [u, v], indicating that task u depends on task v (i.e., task v must be completed before task u). Output Specification Return an array of integers representing one valid order of tasks that can be picked to finish all tasks. The tasks should be in an order such that all prerequisites for a task are met before it appears in the sequence. If it is impossible to finish all tasks (i.e., there is a cyclic dependency), return an empty array. Constraints 1 <= n <= 10^5 0 <= m <= 2 10^5 0 <= u, v < n u != v Sample Test Cases Example 1: Input: Output: Explanation: Given dependencies [0,1], [1,2], [2,3] where [task to do, prerequisite task]. This translates to graph edges: 1 0, 2 1, 3 2. The graph is 3 2 1 0. A valid topological order (tasks that can be started first) is 3, 2, 1, 0. Example 2: Input: Output: Explanation: Given dependencies [1,2], [4,3], [2,4], [4,1]. This translates to graph edges: 2 1, 3 4, 4 2, 1 4. These dependencies form a cycle: 2 1 4 2. Therefore, it is impossible to finish all tasks, and an empty array is returned.