Intuition
Treat each ungrouped item as its own group, topologically sort the groups and the items separately, then lay the items out group by group.
Explanation
Idea
Two rules pull on the answer at once: items in the same group must sit together, and some items must come before others. Handle them on two levels — order the groups, and order the items — then stitch the two orderings together.
First, give every item that belongs to no group (-1) its own brand-new group. Now every item lives in exactly one group, and "same group stays together" is automatic as long as we emit each group's items as a single block.
Build two graphs
For every requirement "j must come before i" (j in beforeItems[i]):
- Add an item edge
j -> i. - If j and i are in different groups, add a group edge
group[j] -> group[i].
Topologically sort both
Run a topological sort (Kahn's algorithm: repeatedly take a node with no unmet prerequisites) on the group graph and on the item graph. If either sort cannot place every node, there is a cycle — the rules contradict each other — so return an empty list.
Stitch
Walk the items in item-topological order and drop each into a bucket for its group. Then emit the groups in group-topological order, and inside each group emit its items in the order they were bucketed. Same-group items land in one contiguous block, and every "before" relation is honoured.
Walk-through
Take n = 6, m = 2, group = [1,1,0,0,-1,-1], beforeItems = [[2],[0],[],[5],[1],[]].
- Items 4 and 5 have no group, so give them fresh groups 2 and 3. Groups now hold g0 = {2,3}, g1 = {0,1}, g2 = {4}, g3 = {5}.
- The "before" pairs are 2 before 0, 0 before 1, 5 before 3, 1 before 4. The cross-group pairs add group edges g0 -> g1 (from 2 before 0), g3 -> g0 (from 5 before 3), and g1 -> g2 (from 1 before 4).
- Group order (always take the smallest group that is ready): g3, g0, g1, g2.
- Item order: 2, 0, 1, 4, 5, 3.
- Bucket the items by group in that order: g0 = [2, 3], g1 = [0, 1], g2 = [4], g3 = [5]. Emit groups in group order g3, g0, g1, g2, giving [5, 2, 3, 0, 1, 4] — a valid arrangement.
Complexity
- Time: O(n + m + E), where E is the total number of "before" relations — every node and edge is touched once across both sorts.
- Space: O(n + m + E) for the two graphs and their in-degree tables.
Implementation
class Solution {
public int[] sortItems(int n, int m, int[] group, int[][] beforeItems) {
// give each ungrouped item its own fresh group
for (int i = 0; i < n; i++) {
if (group[i] == -1) group[i] = m++;
}
java.util.List<java.util.List<Integer>> groupAdj = new java.util.ArrayList<>();
java.util.List<java.util.List<Integer>> itemAdj = new java.util.ArrayList<>();
for (int g = 0; g < m; g++) groupAdj.add(new java.util.ArrayList<>());
for (int i = 0; i < n; i++) itemAdj.add(new java.util.ArrayList<>());
int[] groupIndeg = new int[m];
int[] itemIndeg = new int[n];
java.util.Set<Long> seen = new java.util.HashSet<>();
for (int i = 0; i < n; i++) {
for (int j : beforeItems[i]) {
itemAdj.get(j).add(i);
itemIndeg[i]++;
int gj = group[j], gi = group[i];
if (gj != gi) {
long key = (long) gj * 1000000L + gi;
if (seen.add(key)) {
groupAdj.get(gj).add(gi);
groupIndeg[gi]++;
}
}
}
}
int[] groupOrder = topo(groupAdj, groupIndeg, m);
if (groupOrder == null) return new int[0];
int[] itemOrder = topo(itemAdj, itemIndeg, n);
if (itemOrder == null) return new int[0];
java.util.Map<Integer, java.util.List<Integer>> byGroup = new java.util.HashMap<>();
for (int it : itemOrder) byGroup.computeIfAbsent(group[it], k -> new java.util.ArrayList<>()).add(it);
int[] res = new int[n];
int idx = 0;
for (int g : groupOrder) {
java.util.List<Integer> items = byGroup.get(g);
if (items != null) for (int it : items) res[idx++] = it;
}
return res;
}
private int[] topo(java.util.List<java.util.List<Integer>> adj, int[] indeg, int size) {
java.util.PriorityQueue<Integer> pq = new java.util.PriorityQueue<>();
int[] deg = indeg.clone();
for (int x = 0; x < size; x++) if (deg[x] == 0) pq.offer(x);
int[] order = new int[size];
int c = 0;
while (!pq.isEmpty()) {
int u = pq.poll();
order[c++] = u;
for (int v : adj.get(u)) {
if (--deg[v] == 0) pq.offer(v);
}
}
return c == size ? order : null;
}
}