Problem solution · Python

Divide Nodes into the Maximum Number of Groups

Divide Nodes into the Maximum Number of Groups: 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
124 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 Divide Nodes into the Maximum Number of Groups, 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

  • 124 lines of Python from the credited upstream file divide-nodes-into-the-maximum-number-of-groups.py.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • No explicit loop blocks detected, together with recursive traversal.

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 codeDivide Nodes into the Maximum Number of Groups · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n^2)# Space: O(n) # iterative dfs, bfsclass Solution(object):    def magnificentSets(self, n, edges):        """        :type n: int        :type edges: List[List[int]]        :rtype: int        """        def iter_dfs(u):            group = []            stk = [u]            lookup[u] = 0            while stk:                u = stk.pop()                group.append(u)                for v in adj[u]:                    if lookup[v] != -1:                        if lookup[v] == lookup[u]:  # odd-length cycle, not bipartite                            return []                        continue                    lookup[v] = lookup[u]^1                    stk.append(v)            return group         def bfs(u):            result = 0            lookup = [False]*n            q = [u]            lookup[u] = True            while q:                new_q = []                for u in q:                    for v in adj[u]:                        if lookup[v]:                            continue                        lookup[v] = True                        new_q.append(v)                q = new_q                result += 1            return result            adj = [[] for _ in xrange(n)]        for u, v in edges:            adj[u-1].append(v-1)            adj[v-1].append(u-1)        result = 0        lookup = [-1]*n        for u in xrange(n):            if lookup[u] != -1:                continue            group = iter_dfs(u)            if not group:                return -1            result += max(bfs(u) for u in group)        return result  # Time:  O(n^2)# Space: O(n)# bfsclass Solution2(object):    def magnificentSets(self, n, edges):        """        :type n: int        :type edges: List[List[int]]        :rtype: int        """        def bfs(u):            group = []            q = [u]            lookup[u] = True            while q:                new_q = []                for u in q:                    group.append(u)                    for v in adj[u]:                        if lookup[v]:                            continue                        lookup[v] = True                        new_q.append(v)                q = new_q            return group            def bfs2(u):            result = 0            lookup = [False]*n            q = {u}            lookup[u] = True            while q:                new_q = set()                for u in q:                    for v in adj[u]:                        if v in q:                            return 0                        if lookup[v]:                            continue                        lookup[v] = True                        new_q.add(v)                q = new_q                result += 1            return result            adj = [[] for _ in xrange(n)]        for u, v in edges:            adj[u-1].append(v-1)            adj[v-1].append(u-1)        result = 0        lookup = [0]*n        for u in xrange(n):            if lookup[u]:                continue            group = bfs(u)            mx = 0            for u in group:                d = bfs2(u)                if d == 0:                    return -1                mx = max(mx, d)            result += mx        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 ↗