Sort Items by Groups Respecting Dependencies

There are n items, each belonging to zero or one of m groups. The array group[i] represents the group that the i-th item belongs to. If group[i] == -1, it means the i-th item belongs to no group and is completely independent. The items and the groups are zero-indexed.

Return a sorted list of the items such that:

  • The items that belong to the same group are strictly next to each other in the sorted list.
  • There are specific dependency relations defined by beforeItems, where beforeItems[i] is a list containing all the items that must come before the i-th item in the final sorted array.

Return any valid sorted list if there is more than one solution. Return an empty list if no valid solution exists (e.g., due to cyclic dependencies).

Example 1:

Input: n = 4, m = 1, group = [-1,-1,-1,-1], beforeItems = [[1,2,3],[],[1],[1,2]]

Output: [1,2,3,0]

Explanation:

Every single item has group[i] == -1, meaning there are no group constraints at all. The problem becomes a standard, single-level topological sort. The dependencies strictly force the exact order: 1 -> 2 -> 3 -> 0.

Example 2:

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

Output: [ ]

Explanation:

Item 4 must come before 6, 6 before 3, and 3 before 4. This forms an infinite cycle (4 -> 6 -> 3 -> 4). Since topological sort is impossible on a cycle, we return an empty array.

Now Your Turn!

Pick the correct output for the given input

Input: n = 5, m = 2, group = [0,0,1,1,0], beforeItems = [[2,3],[],[],[],[1,3]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= m <= n <= 3*104
  • group.length == beforeItems.length == n
  • -1 <= group[i] <= m - 1
  • 0 <= beforeItems[i].length <= n - 1
  • 0 <= beforeItems[i][j] <= n - 1
  • i != beforeItems[i][j]
  • beforeItems[i] does not contain duplicate elements.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> sortItems(int n, int m, vector<int>& group, vector<vector<int>>& beforeItems) {
// Write your code here
}
};
Test Case

Input:

Before Items
Group
M
N