#2493
Divide Nodes Into the Maximum Number of Groups
HardDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph Traversal (BFS/DFS)Bipartite Graph Checking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + e) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + e)Space O(n)
The optimal solution leverages the concept of bipartite graphs. We can use BFS or DFS to color the graph and determine if it can be divided into two groups. If it can, we can then calculate the maximum number of groups based on the bipartite nature.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a color array to store group assignments for each node.
- 2Step 2: For each unvisited node, perform BFS or DFS to color the graph with two colors.
- 3Step 3: If a conflict is found (two adjacent nodes have the same color), return -1.
- 4Step 4: Count the number of nodes in each color and return the total number of groups as the sum of the counts.
solution.py33 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def maxGroupsOptimal(n, edges):
5 graph = defaultdict(list)
6 for a, b in edges:
7 graph[a].append(b)
8 graph[b].append(a)
9 color = [-1] * (n + 1)
10 max_groups = 0
11
12 def bfs(start):
13 queue = deque([start])
14 color[start] = 0
15 count = [1, 0]
16 while queue:
17 node = queue.popleft()
18 for neighbor in graph[node]:
19 if color[neighbor] == -1:
20 color[neighbor] = 1 - color[node]
21 count[color[neighbor]] += 1
22 queue.append(neighbor)
23 elif color[neighbor] == color[node]:
24 return -1
25 return count[0] + count[1]
26
27 for i in range(1, n + 1):
28 if color[i] == -1:
29 result = bfs(i)
30 if result == -1:
31 return -1
32 max_groups += result
33 return max_groupsℹ
Complexity note: The time complexity is O(n + e), where n is the number of nodes and e is the number of edges, due to the BFS traversal of the graph. Space complexity is O(n) for storing the graph and color arrays.
- 1The problem can be reduced to checking if the graph is bipartite.
- 2Each connected component can be processed independently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.