AlgoInsight

DSA problem

Sort Items by Groups Respecting Dependencies

HardTopological SortPattern: Topological Sorttop300GoogleAmazonMetaMicrosoftBloomberg

There are n items each belonging to zero or one of m groups, where group[i] is the group identifier of item i and -1 means the item belongs to no group. The items and the groups are zero-indexed. You are also given a list beforeItems where beforeItems[i] lists items that must appear before item i in the final ordering. Return any solution that satisfies all the following: items in the same group are adjacent in the order, and the item-level "before" constraints are respected. Return an empty array if no such order exists.

The challenge is that ordering operates on two intertwined levels — items inside a group must be contiguous (a group-level order) AND the per-item dependencies cut across groups (an item-level order). The clean way to handle this is two coupled topological sorts.

First, assign every ungrouped item (group[i] == -1) a unique fresh group id so that every item now lives in some group. Next, walk beforeItems once: each dependency b → a either connects items inside the same group (an item-level edge) or connects different groups (a group-level edge groupOf(b) → groupOf(a)). Build two DAGs from these edges, with separate in-degree arrays per level.

Run Kahn's BFS to obtain a topological order of the groups, then run Kahn's BFS over items but seed each group's queue with its own zero-in-degree items, producing a per-group item order. Finally walk the groups in their topo order and emit each group's items in their per-group topo order. If either Kahn's run cannot consume all of its nodes, a cycle existed and the answer is the empty array. Total complexity is O(n + m + dependencies), which is asymptotically optimal.

Examples

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]
Explanation: A valid order: items in group 0 (3, 4, 6) are contiguous, items in group 1 (2, 5) are contiguous, and every "before" constraint is satisfied.
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 6 must come before item 3, item 3 before item 4, and item 4 before item 6 — a cycle exists, so no valid order is possible.
Example 3
Input: n = 5, m = 1, group = [0,0,0,0,0], beforeItems = [[1],[2],[3],[4],[]]
Output: [4,3,2,1,0]
Explanation: All five items are in group 0. The dependencies form a chain 4 → 3 → 2 → 1 → 0, which is the only valid order.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

graphtopological-sortbfsdag

Browse all DSA problems