<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 defaultdict
class Solution:

    def topologicalSort(self, adj_list, nodes):
        in_deg = {}

        for node in nodes:
            in_deg[node] = 0

        for node in adj_list:
            for vert in adj_list[node]:
                in_deg[vert] += 1
        
        q = []

        for node in in_deg:
            if in_deg[node] == 0:
                q.append(node)
        
        result = []

        while q:
            node = q.pop(0)
            result.append(node)

            for vert in adj_list[node]:
                in_deg[vert] -= 1
                if in_deg[vert] == 0:
                    q.append(vert)

        if len(result) != len(nodes):
            return -1
        
        return result

    def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:

        groups_to_nodes = defaultdict(list)
        nodes_to_groups = defaultdict(int)
        for i in range(n):
            groups_to_nodes[group[i]].append(i)
            nodes_to_groups[i] = group[i]

        # group_to_adj_list = defaultdict(dict)
        group_to_adj_list = {}

        for i in range(m):
            group_to_adj_list[i] = defaultdict(list)

        for i in range(m):
            for node in groups_to_nodes[i]:
                
                for bf in beforeItems[node]:
                    if bf in groups_to_nodes[i]:
                        if bf in group_to_adj_list[i]:
                            group_to_adj_list[i][bf].append(node)
                        else:
                            group_to_adj_list[i][bf] = [node]



        print(group_to_adj_list)

        group_to_internal_order = {}
        
        for i in range(m):
            nodes = groups_to_nodes[i]
            adj_list = group_to_adj_list[i]
            output = self.topologicalSort(adj_list, nodes)
            print("OUTPUT", i, output)
            if output == -1:
                # print("HERE")
                return []
            group_to_internal_order[f"G{i}"] = output
            # print(self.topologicalSort(adj_list, nodes))
            
        print(group_to_internal_order, "HERE")

        final_adj_list = defaultdict(set)

        remaining_nodes = set()

        for i in range(n):

            if group[i] == -1:
                remaining_nodes.add(i)
            else:
                remaining_nodes.add(f'G{group[i]}')

            for node in beforeItems[i]:
                node_group = nodes_to_groups[node]

                if node_group != group[i]:

                    node_group_key = None
                    i_group_key = None

                    if node_group == -1:
                        node_group_key = node
                    else:
                        node_group_key = f'G{node_group}'
                    
                    if group[i] == -1:
                        i_group_key = i
                    else:
                        i_group_key = f'G{group[i]}'

                    final_adj_list[node_group_key].add(i_group_key)


            # print(i)
        print(final_adj_list)
        print(remaining_nodes)

        final_order = self.topologicalSort(final_adj_list, remaining_nodes)
        if final_order == -1:
            return []
        print(final_order)

        # return [6, 3,4,1,0,7,5,2]
        # return [0, 7, 5, 2, 6, 3, 4, 1]

        final_result = []

        for i in final_order:
            if type(i) == int:
                # print("HELLO")
                final_result.append(i)
            else:
                final_result.extend(group_to_internal_order[i])
        return final_result
        
498