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

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



        # put elements in their respective group. Also keep track of a free_group value which starts
        # equal to m. When we see a -1, put the item in the next free group, increment value of 
        # free_group. Change the group[i] value to the free group so later we know where it is
        
        # Problem is nest topological problem. We need to choose a group whose elements to put
        # next in the sorted list. If the group has a before value not yet visited, we can't choose
        # that group next.


        # key is group id, value is set of items in that group
        groups = defaultdict(set)

        # key is item, value is item group
        item_groups = dict()
        next_group = m
        
        
        # when a group's indegrees is 0, it can be added to output
        group_indegrees = defaultdict(int)

        # tells us relationships between items. Key is an item, value is a set of items
        # that key needs to come before
        item_graph = defaultdict(set)
        item_indegrees = defaultdict(int)

        # for topological sorting, an item can only be visited once its indegrees is 0 (everything
        # that points to it has been visited)

        for item in range(n):
            item_group = group[item]

            # if item does not have a group, assign it one by itself
            if item_group == -1:
                item_group = next_group
                next_group += 1

                
            # add item to its group
            curr_group = groups[item_group]
            curr_group.add(item)
            groups[item_group] = curr_group

            item_groups[item] = item_group

        # add group and item relationships based on beforeItems
        for item, before_items in enumerate(beforeItems):
            item_group = item_groups[item]
            for before_item in before_items:
                before_group = item_groups[before_item]

                # increase item indegree by 1
                item_indegrees[item] = item_indegrees[item] + 1

                # items groups have 1 more indegree, if the before item is not in the same group
                if item_group != before_group:
                    group_indegrees[item_group] = group_indegrees[item_group] + 1

                # make before item point to current item
                before_item_edges = item_graph[before_item]
                before_item_edges.add(item)
                item_graph[before_item] = before_item_edges


        # since groups must be placed in output together, we visit groups at a time instead of 
        # individual elements. Any group with indegree of 0 (no group required to come before)
        # can be added to queue

        group_queue = deque()
        for group in groups.keys():
            if group_indegrees[group] == 0:
                group_queue.append(group)
        
        output = []
        
        while len(group_queue) > 0:

            curr_group_id = group_queue.popleft()
            curr_group = groups[curr_group_id]

            
            # choose which item within the current group can start the queue. An item can be added
            # to the queue if its indegree is 0
            item_queue = deque()

            for item in curr_group:
                if item_indegrees[item] == 0:
                    item_queue.append(item)
            
            while len(item_queue) > 0:
                
                item = item_queue.popleft()
                output.append(item)

                # get items that required current item to come before them, decrease their indegrees since
                # current has been visited. If this causes their indegrees to equal 0 and items are in the 
                # same group, add item to item queue. Also decrease after item's group indegrees. If 
                # that group's indegrees is now 0, they can be added to the output whenever possible, add 
                # group to group queue

                for after_item in item_graph[item]:
                    after_item_group = item_groups[after_item]
                    item_indegrees[after_item] = item_indegrees[after_item] - 1

                    if item_indegrees[after_item] == 0 and after_item_group == curr_group_id:
                        item_queue.append(after_item)

                    group_indegrees[after_item_group] = group_indegrees[after_item_group] - 1
                    if group_indegrees[after_item_group] == 0:
                        group_queue.append(after_item_group)  

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


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