Watch 10 video solutions for Sort Items by Groups Respecting Dependencies, a hard level problem involving Depth-First Search, Breadth-First Search, Graph. This walkthrough by codestorywithMIK has 9,825 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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:
beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-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 * 104group.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.Problem Overview: You are given n items where some belong to groups. Certain items depend on others and must appear later in the ordering. The goal is to return a valid ordering where item dependencies are respected and items from the same group appear together.
Approach 1: Topological Sort with Grouped Items (O(n + m) time, O(n + m) space)
This problem is essentially a dependency graph with an extra constraint: items should be ordered within groups, and groups themselves may depend on other groups. The clean solution builds two graphs. First, assign unique group IDs to items that initially have no group. Then construct a group-level dependency graph and an item-level dependency graph. Run topological sort on groups first, and within each group run another topological sort for its items. By separating group ordering from item ordering, you enforce both dependency rules without mixing constraints. This approach relies heavily on topological sort and general graph traversal techniques.
The key insight: item dependencies sometimes imply group dependencies. When item a depends on item b and they belong to different groups, create an edge between those groups. Once group order is resolved, items inside each group can be sorted independently using the same dependency edges.
Approach 2: Using Priority Queues for Topological Sorting (O((n + m) log n) time, O(n + m) space)
This variation still models the problem as two dependency graphs but uses a priority queue while performing topological sorting. Instead of processing nodes in arbitrary order, nodes with zero in-degree are pushed into a min-heap. This guarantees deterministic ordering when multiple valid nodes are available. The technique works with either breadth-first search style Kahn's algorithm or a modified queue-based traversal. The tradeoff is additional log n cost due to heap operations.
The heap-based approach is useful when deterministic output order is preferred or when platforms require lexicographically smaller valid sequences. Otherwise, the standard queue-based topological sort is faster and simpler.
Recommended for interviews: The grouped topological sort solution is what most interviewers expect. It demonstrates strong graph modeling skills: recognizing two dependency layers and solving them separately. Building both graphs and running Kahn's algorithm in O(n + m) shows you understand dependency resolution and scalable graph traversal.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Topological Sort with Grouped Items | O(n + m) | O(n + m) | General optimal solution when resolving dependencies across grouped items |
| Priority Queue Based Topological Sort | O((n + m) log n) | O(n + m) | When deterministic or lexicographically ordered valid results are preferred |