 All Problems
Sort Items by Groups Respecting Dependencies
hard
topological sort
graph
google
amazon
facebook

There are n items each belonging to a group (or group -1 = its own group). You are given beforeItems where beforeItems[i] lists items that must come before item i.

Return a permutation of items that satisfies all constraints, or an empty array if impossible.

Example 1:

Input: n=8, m=2, group=[-1,-1,1,0,0,1,0,-1], beforeItems=[[],[6],[5],[6],[3,6],[],[],[]]
Output: [6,3,4,1,5,2,0,7]

Constraints:

  • 1 <= n <= 3 * 10^4
  • group.length == beforeItems.length == n
Run to check your code against the sample cases, or submit to run every case