Sort Items by Groups Respecting Dependencies Problem
Description
LeetCode Problem 1203.
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:
- The items that belong to the same group are next to each other in the sorted list.
- There are some relations between these items where
beforeItems[i]is a list containing all the items that should come before thei-th item in the sorted array (to the left of thei-th item).
Return any solution if there is more than one solution and return an empty list if there is no solution.
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]
Example 2:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
Constraints:
1 <= m <= n <= 3 * 10^4group.length == beforeItems.length == n-1 <= group[i] <= m - 10 <= beforeItems[i].length <= n - 10 <= beforeItems[i][j] <= n - 1i != beforeItems[i][j]beforeItems[i]does not contain duplicates elements.
Solution
Approach: Two-Level Topological Sort
One topological sort over all items respects the beforeItems rules, but it can spread a group's items apart. Instead, sort at two levels: first decide the order of the groups, then the order of the items inside each group.
- Every item gets a group. An item with
group[i] = -1is put in a new group of its own (m,m + 1, ...). Now every item belongs to exactly one group, and every group must be contiguous. - Build two graphs from each rule "
jbeforei":- If
iandjare in the same group, add the item edgej -> i. - Otherwise add the group edge
group[j] -> group[i]: all ofj's group must come before all ofi's group, because groups cannot interleave.
- If
- Topologically sort the groups (Kahn's algorithm: repeatedly take a node with no remaining incoming edges). If some groups are left over, there is a cycle between groups and no answer.
- For each group in that order, topologically sort its items using the item edges. A cycle inside a group also means no answer.
- Write out the groups' item orders one after another.
The example shows why the group graph matters. Item 4 depends on item 3, both in group 0, so that rule is an item edge. But making 4 come before 6 creates a cycle 6 -> 3 -> 4 -> 6 inside group 0, and the answer is empty. In the same way, two groups that each need something from the other form a group cycle, even if no single item depends on itself. Groups with no items simply become isolated nodes in the group graph.
Complexity: O(n + m + E) time and space, where E is the total length of beforeItems.
from collections import deque
class Solution:
def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
# Give every item without a group a group of its own.
group = list(group)
for i in range(n):
if group[i] == -1:
group[i] = m
m += 1
group_items = [[] for _ in range(m)]
for i in range(n):
group_items[group[i]].append(i)
# Two graphs: items inside the same group, and groups among themselves.
item_next = [[] for _ in range(n)]
item_indeg = [0] * n
group_next = [[] for _ in range(m)]
group_indeg = [0] * m
for i in range(n):
for j in beforeItems[i]: # j must come before i
if group[i] == group[j]:
item_next[j].append(i)
item_indeg[i] += 1
else:
group_next[group[j]].append(group[i])
group_indeg[group[i]] += 1
def topo_sort(nodes: List[int], nxt: List[List[int]], indeg: List[int]) -> List[int]:
"""Kahn's algorithm on the given nodes; [] if they contain a cycle."""
queue = deque(v for v in nodes if indeg[v] == 0)
order = []
while queue:
v = queue.popleft()
order.append(v)
for w in nxt[v]:
indeg[w] -= 1
if indeg[w] == 0:
queue.append(w)
return order if len(order) == len(nodes) else []
group_order = topo_sort(list(range(m)), group_next, group_indeg)
if not group_order:
return []
ans = []
for g in group_order:
items = group_items[g]
order = topo_sort(items, item_next, item_indeg)
if len(order) != len(items):
return []
ans.extend(order)
return ans