Course Schedule I

Graphs Hard Problems Hard
  • This problem mimics the concept of handling dependencies in project management and software development tools
  • For instance, in package managers like npm (Node Package Manager), a package can't be installed before its dependencies are resolved
  • Similarly, in project management tools like Jira, certain tasks may be blocked until prerequisite tasks are completed
  • This problem essentially deals with a directed graph and a cycle detection which is similar to detection of cyclic dependencies in real life software development

There are a total of N tasks, labeled from 0 to N-1. Given an array arr where arr[i] = [a, b] indicates that you must take course b first if you want to take course a. Find if it is possible to finish all tasks.

Examples:

Input: N = 4, arr = [[1,0],[2,1],[3,2]]


Output: True


Explanation: It is possible to finish all the tasks in the order : 0 1 2 3.

First, we will finish task 0. Then we will finish task 1, task 2, and task 3.

Input: N = 4, arr = [[0,1],[3,2],[1,3],[3,0]]


Output: False


Explanation: It is impossible to finish all the tasks. Let’s analyze the pairs:

For pair {0, 1} -> we need to finish task 1 first and then task 0. (order : 1 0).

For pair{3, 2} -> we need to finish task 2 first and then task 3. (order: 2 3).

For pair {1, 3} -> we need to finish task 3 first and then task 1. (order: 3 1).

But for pair {3, 0} -> we need to finish task 0 first and then task 3 but task 0 requires task 1 and task 1 requires task 3. So, it is not possible to finish all the tasks.

Input: N = 2, arr = [[1,0]]

Constraints

  •   1 <= N <= 2000
  •   0 <= arr.length <= 5000
  •   arr[i].length == 2
  •   0 <= arr[i][0], arr[i][1] < N
  •   All the pairs arr[i] are unique.

Hints

  • "Construct the graph using an adjacency list. Compute the in-degree (number of prerequisites) for each node. Use Kahn’s Algorithm (BFS) to process nodes with zero in-degree (no prerequisites). If we can process all N tasks, return True; otherwise, return False (cycle exists)."
  • "Use DFS with a recursion stack to detect back edges (which indicate a cycle). If a cycle is found, return False; otherwise, return True."

Company Tags

Visa McKinsey & Company Red Hat AMD Optum Chewy Morgan Stanley KPMG Flipkart Etsy Target American Express Salesforce Stripe Teladoc Health Byju's Square Unity Technologies Epic Games Pinterest eBay Boston Consulting Group PwC Freshworks Rakuten Google Microsoft Amazon Meta Apple Netflix Adobe