<p>There are&nbsp;<code>n</code>&nbsp;items each&nbsp;belonging to zero or one of&nbsp;<code>m</code>&nbsp;groups where <code>group[i]</code>&nbsp;is the group that the <code>i</code>-th item belongs to and it&#39;s equal to <code>-1</code>&nbsp;if the <code>i</code>-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.</p>

<p>Return a sorted list of the items such that:</p>

<ul>
	<li>The items that belong to the same group are next to each other in the sorted list.</li>
	<li>There are some&nbsp;relations&nbsp;between these items where&nbsp;<code>beforeItems[i]</code>&nbsp;is a list containing all the items that should come before the&nbsp;<code>i</code>-th item in the sorted array (to the left of the&nbsp;<code>i</code>-th item).</li>
</ul>

<p>Return any solution if there is more than one solution and return an <strong>empty list</strong>&nbsp;if there is no solution.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/09/11/1359_ex1.png" style="width: 191px; height: 181px;" /></strong></p>

<pre>
<strong>Input:</strong> n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
<strong>Output:</strong> [6,3,4,1,5,2,0,7]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
<strong>Output:</strong> []
<strong>Explanation:</strong>&nbsp;This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= m &lt;= n &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>group.length == beforeItems.length == n</code></li>
	<li><code>-1 &lt;= group[i] &lt;= m - 1</code></li>
	<li><code>0 &lt;= beforeItems[i].length &lt;= n - 1</code></li>
	<li><code>0 &lt;= beforeItems[i][j] &lt;= n - 1</code></li>
	<li><code>i != beforeItems[i][j]</code></li>
	<li><code>beforeItems[i]&nbsp;</code>does not contain&nbsp;duplicates elements.</li>
</ul>

from collections import deque, defaultdict
from typing import List

class Solution:
    def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
        # After:[before] map
        before_map = {i: [] for i in range(n)}
        for i in range(n):
            for beforeItem in beforeItems[i]:
                before_map[beforeItem].append(i)

        # Assign unique group IDs to ungrouped items
        new_group_id = m
        for i in range(n):
            if group[i] == -1:
                group[i] = new_group_id
                new_group_id += 1

        # Get groups with their items
        def get_groups():
            groups = defaultdict(list)
            for i in range(n):
                groups[group[i]].append(i)
            return groups

        groups = get_groups()

        # Topological sorting of items within a group
        def get_reordered_group(grp):
            indegree = [0] * n
            for i in grp:
                for before in beforeItems[i]:
                    if before in grp:
                        indegree[i] += 1
            
            q = deque([i for i in grp if indegree[i] == 0])
            reordered_group = []

            while q:
                val = q.popleft()
                reordered_group.append(val)
                for after in before_map[val]:
                    if after in grp:
                        indegree[after] -= 1
                        if indegree[after] == 0:
                            q.append(after)

            # Check if there's a cycle
            if len(reordered_group) != len(grp):
                return []

            return reordered_group

        # Reorder each group
        for grp in groups:
            reordered = get_reordered_group(groups[grp])
            if not reordered:
                return []  # Cycle detected
            groups[grp] = reordered

        # Map of group dependencies
        group_graph = defaultdict(list)
        group_indegree = defaultdict(int)

        # Building group dependencies
        for curr in range(n):
            for prev in beforeItems[curr]:
                if group[prev] != group[curr]:
                    group_graph[group[prev]].append(group[curr])
                    group_indegree[group[curr]] += 1

        # Topological sort for groups
        def topological_sort(graph, indegree, nodes):
            q = deque([node for node in nodes if indegree[node] == 0])
            sorted_order = []
            while q:
                node = q.popleft()
                sorted_order.append(node)
                for neighbor in graph[node]:
                    indegree[neighbor] -= 1
                    if indegree[neighbor] == 0:
                        q.append(neighbor)
            if len(sorted_order) != len(nodes):
                return []  # Cycle detected
            return sorted_order

        # Perform topological sort on groups
        sorted_groups = topological_sort(group_graph, group_indegree, groups.keys())
        if not sorted_groups:
            return []  # Cycle detected

        # Combine sorted items in the order of sorted groups
        result = []
        for grp in sorted_groups:
            result.extend(groups[grp])

        return result

510