Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Course Schedule

Medium Acceptance 51.77% Points 30.00

You are given n tasks, labeled from 0 to n-1, and a list of m prerequisite pairs. Each pair [a, b] indicates that task a depends on task b and must be completed after it. Your goal is to determine an order in which to complete all the tasks.

  • There may be multiple valid orders; return any one of them.
  • If it is impossible to complete all tasks due to circular dependencies, return an empty array. The driver code will print "No Ordering Possible" when this happens.
  • If a valid order is returned, the output will be 1. If the order is invalid, the output will be 0.

The task is to complete the function findOrder() which takes two integers n, and m and a list of lists of size m*2 denoting the prerequisite pairs as input and returns any correct order to finish all the tasks. Return an empty array if it's impossible to finish all tasks.

Examples
Example 1

Example 1

Input: n = 4, m = 2, prerequisites = {{1, 0}, {2, 0}}

Output: 1

Explanation: One possible order is [0, 1, 2, 3]. Tasks 1 and 2 must be completed after task 0, and task 3 can be done last.

Example 2

Example 2

Input: n = 3, m = 2, prerequisites = {{0, 1}, {1, 2}}

Output: 1

Explanation: One possible order is [2, 1, 0]. Task 2 can be done first, followed by task 1, and finally task 0.

Hints
Hint 1
Expected Time Complexity: O(n+m).
Hint 2
Expected Auxiliary Space: O(n+m).
Constraints
  • 1 = n = 10^5
  • 0 = m = min(n*(n-1),10^5)
  • 0 = prerequisites[i][0], prerequisites[i][1] < n
  • All prerequisite pairs are unique
  • prerequisites[i][0] ? prerequisites[i][1]
Companies
Google
Topics
Graph BFS DFS
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions