Problem Description
You are given n
items each belonging to zero or one of m
groups, where group[i]
indicates the group of the i
-th item, and it's equal to -1
if the item belongs to no group. Additionally, you have a list beforeItems[i]
which contains all the items that should come before the i
-th item in the sorted array. Your task is to return a sorted list of items such that:
- Items that belong to the same group are next to each other.
- The order of items respects the given dependencies.
If there is no valid sorting, return an empty list.
Key Insights
- The problem can be modeled as a directed graph where each item is a node, and directed edges represent the dependency from
beforeItems[i]
toi
. - We can utilize topological sorting to determine a valid order of items.
- Groups can also be treated as nodes, and we may need to perform topological sorting on groups as well to maintain group order.
Space and Time Complexity
Time Complexity: O(n + m) for processing nodes and edges in the graph.
Space Complexity: O(n + m) for storing the adjacency lists and in-degree counts.
Solution
The solution involves the following steps:
- Graph Construction: Build a directed graph where each item points to its dependencies based on
beforeItems
. Additionally, maintain a mapping of items to their respective groups. - Topological Sort for Items: Perform a topological sort on the items to determine a valid order that respects the dependencies.
- Group Processing: After obtaining the sorted order of items, group the items based on their group assignments and then perform a topological sort on these groups.
- Final Output: Construct the final output by concatenating the sorted items of each group in the order determined by the group topological sort.