<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>

# Implementation of Queue
class Queue:
    def __init__(self):
        self.queue = []
    def enqueue(self,v):
        self.queue.append(v)
    def isempty(self):
        return(self.queue == [])
    def dequeue(self):
        v = None
        if not self.isempty():
            v = self.queue[0]
            self.queue = self.queue[1:]
        return(v)    
    def __str__(self):
        return(str(self.queue))

class Solution:
    # Creates a dictionary that returns all elements of a particular group. Used in the main algorithm when we are listing all the items # that belong to a group side by side
    def get_group_wise_elements(self, group, m):
        group_wise_elements = { i:[] for i in range(m) }
        for i in range(len(group)):
            grp = group[i] if group[i] >= 0 else -i-1
            if grp not in group_wise_elements:
                group_wise_elements[grp] = []
            group_wise_elements[grp].append(i)
        return group_wise_elements

    # Convert the problem into two graphs- group_graph and items_graph. Along with it, return indegrees for each node in both the graphs. 
    def preprocessing(self, beforeItems, group, m, n, groupwise_items):
        group_indegree, items_indegree = {}, {i:0 for i in range(n)}
        items_alist =  {i:[] for i in range(n)}
        group_alist = {}

        for key in groupwise_items:
            group_alist[key] = set()
            group_indegree[key] = 0
 
        for i in range(len(beforeItems)):
            before = beforeItems[i]
            for num in before:
                if num not in items_alist:
                    items_alist[num] = [ ]
                items_alist[num].append(i)
                items_indegree[i] += 1

                grp_num = group[num] if group[num] >= 0 else -num-1
                grp_i = group[i] if group[i] >= 0 else -i-1  
                if grp_num != grp_i:
                    if grp_num not in group_alist:
                        group_alist[grp_num] = set()
                    group_alist[grp_num].add(grp_i)
        
        for key in group_alist.keys():
            group_alist[key] = list(group_alist[key])

        for u in group_alist.keys():
            for v in group_alist[u]:
                if v not in group_indegree:
                    group_indegree[v] = 0
                group_indegree[v] += 1

        return items_alist, group_alist, items_indegree, group_indegree

    # Run the actual nested topological sorting algorithm
    def lpath(self, items_alist, group_alist, items_indegree, group_indegree, groupwise_items, n, group):
        output = [ ]

        grp_queue = Queue()
        items_queue = Queue()

        for grp in group_indegree:
            if group_indegree[grp] == 0:
                grp_queue.enqueue(grp)

        # Outer topological sort is for groups
        while not grp_queue.isempty():
            curr_grp = grp_queue.dequeue()
            group_indegree[curr_grp] -= 1
            for adj_grp in group_alist[curr_grp]:
                # Reduce the indegree of each adjacent group of the removed vertex by 1
                group_indegree[adj_grp] -= 1

                # If after reducing the degree of adjacent group, it becomes zero then insert it into the group queue
                if group_indegree[adj_grp] == 0 :
                    grp_queue.enqueue(adj_grp)

            for i in groupwise_items[curr_grp]:
                if items_indegree[i] == 0 :
                    items_queue.enqueue(i)

            # Inner topological sort is for the items
            while (not items_queue.isempty()):

                # Remove one vertex from items queue which have zero degree items and reduce the indegree by 1
                curr_vertex = items_queue.dequeue()
                output.append(curr_vertex)
                items_indegree[curr_vertex] = items_indegree[curr_vertex] - 1
                
                # Repeat for each adjacent of the removed item 
                for adj_vertex in items_alist[curr_vertex]:
                    # Reduce the indegree of each adjacent of the removed item by 1
                    items_indegree[adj_vertex] = items_indegree[adj_vertex] - 1

                    # If after reducing the degree of adjacent item, it becomes zero then insert it into the items queue
                    if items_indegree[adj_vertex] == 0 and group[adj_vertex] == curr_grp:
                        items_queue.enqueue(adj_vertex)

        if len(output) != n: return []
        return output

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

        items_alist, group_alist, items_indegree, group_indegree = self.preprocessing(beforeItems,group, m, n, group_wise_items)
        
        return self.lpath(items_alist, group_alist, items_indegree, group_indegree, group_wise_items, n, group)

536