Problem solution · Python

Sort Items by Groups Respecting Dependencies

Sort Items by Groups Respecting Dependencies: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
76 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeSort Items by Groups Respecting Dependencies · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n + e)# Space: O(n + e) import collections  class Topo(object):    def __init__(self):        self.__nodes = set()        self.__in_degree = collections.defaultdict(set)        self.__out_degree = collections.defaultdict(set)            def add_node(self, node):        self.__nodes.add(node)        def add_edge(self, src, dst):        self.add_node(src), self.add_node(dst)        self.__in_degree[dst].add(src)        self.__out_degree[src].add(dst)        def sort(self):        q = collections.deque()        result = []        for node in self.__nodes:            if node not in self.__in_degree:                q.append(node)        while q:            node = q.popleft()            result.append(node)            for nei in self.__out_degree[node]:                self.__in_degree[nei].remove(node)                if not self.__in_degree[nei]:                    self.__in_degree.pop(nei)                    q.append(nei)        if len(result) < len(self.__nodes):            return        return result  class Solution(object):    def sortItems(self, n, m, group, beforeItems):        """        :type n: int        :type m: int        :type group: List[int]        :type beforeItems: List[List[int]]        :rtype: List[int]        """        for i in xrange(n):            if group[i] == -1:                group[i] = m                m += 1            global_group = Topo()        for i in xrange(m):            global_group.add_node(i)        local_groups = collections.defaultdict(Topo)        for i in xrange(n):            local_groups[group[i]].add_node(i)        for i in xrange(n):            for j in beforeItems[i]:                if group[i] == group[j]:                    local_groups[group[i]].add_edge(j, i)                else:                    global_group.add_edge(group[j], group[i])        result = []        global_order = global_group.sort()        if global_order is None:            return []        for i in global_order:            local_order = local_groups[i].sort()            if local_order is None:                return []            for x in local_order:                result.append(x)        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗