Two-level topological sort.
First, assign each -1 group item to its own unique group. This simplifies handling.
Build two graphs:
- Item graph: edges between items based on
beforeItems. - Group graph: if item
a(group X) depends on itemb(group Y) where X ≠ Y, add edge Y → X.
Topologically sort the group graph to get group order. Then, for each group, topologically sort its items.
Concatenate the sorted items in group order.