Approach
Breadth-first search
For Sort Items by Groups Respecting Dependencies, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 76 lines of Python from the credited upstream file sort-items-by-groups-respecting-dependencies.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 7class Topo(object):8 def __init__(self):9 self.__nodes = set()10 self.__in_degree = collections.defaultdict(set)11 self.__out_degree = collections.defaultdict(set)12 13 def add_node(self, node):14 self.__nodes.add(node)15 16 def add_edge(self, src, dst):17 self.add_node(src), self.add_node(dst)18 self.__in_degree[dst].add(src)19 self.__out_degree[src].add(dst)20 21 def sort(self):22 q = collections.deque()23 result = []24 for node in self.__nodes:25 if node not in self.__in_degree:26 q.append(node)27 while q:28 node = q.popleft()29 result.append(node)30 for nei in self.__out_degree[node]:31 self.__in_degree[nei].remove(node)32 if not self.__in_degree[nei]:33 self.__in_degree.pop(nei)34 q.append(nei)35 if len(result) < len(self.__nodes):36 return37 return result38 39 40class Solution(object):41 def sortItems(self, n, m, group, beforeItems):42 """43 :type n: int44 :type m: int45 :type group: List[int]46 :type beforeItems: List[List[int]]47 :rtype: List[int]48 """49 for i in xrange(n):50 if group[i] == -1:51 group[i] = m52 m += 1 53 global_group = Topo()54 for i in xrange(m):55 global_group.add_node(i)56 local_groups = collections.defaultdict(Topo)57 for i in xrange(n):58 local_groups[group[i]].add_node(i)59 for i in xrange(n):60 for j in beforeItems[i]:61 if group[i] == group[j]:62 local_groups[group[i]].add_edge(j, i)63 else:64 global_group.add_edge(group[j], group[i])65 result = []66 global_order = global_group.sort()67 if global_order is None:68 return []69 for i in global_order:70 local_order = local_groups[i].sort()71 if local_order is None:72 return []73 for x in local_order:74 result.append(x)75 return result76