Hard
DFS
BFS
Graph
Topological Sort
1203. Sort Items by Groups Respecting Dependencies
There are n
items each belonging to zero or one of m
groups where group[i]
is the group that the i-th item belongs to and it's equal to -1
if the i
-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
beforeItems[i]
is a list containing all the items that should come before the i
-th item in the sorted array (to the left of the i
-th item).Return any solution if there is more than one solution and return an empty list if there is no solution.
Example 1:
Example 2:
Constraints:
m
<= n
<= 3 * 104group.length
== beforeItems.length
== n
group[i]
<= m
- 1beforeItems[i].length
<= n
- 1beforeItems[i][j]
<= n
- 1i
!= beforeItems[i][j]
beforeItems[i]
does not contain duplicates elements.