Divide Nodes Into the Maximum Number of Groups - Problem

You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n.

You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected.

Divide the nodes of the graph into m groups (1-indexed) such that:

  • Each node in the graph belongs to exactly one group.
  • For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1.

Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.

Input & Output

Example 1 — Path Graph
$ Input: n = 6, edges = [[1,2],[1,3],[2,4],[4,5],[4,6]]
Output: 4
💡 Note: The graph forms a tree. We can assign: node 3→group 1, node 1→group 2, node 2→group 3, nodes 4→group 4. Adjacent nodes differ by exactly 1 group.
Example 2 — Triangle (Odd Cycle)
$ Input: n = 3, edges = [[1,2],[2,3],[3,1]]
Output: -1
💡 Note: This forms a triangle (3-cycle). It's impossible to assign groups where adjacent nodes always differ by 1, since we'd need 1→2→3→1 which is impossible.
Example 3 — Disconnected Components
$ Input: n = 4, edges = [[1,2],[3,4]]
Output: 2
💡 Note: Two separate edges: 1-2 and 3-4. Each component needs 2 groups. Maximum across all components is 2.

Constraints

  • 1 ≤ n ≤ 15
  • 0 ≤ edges.length ≤ n * (n - 1) / 2
  • edges[i].length == 2
  • 1 ≤ ai, bi ≤ n
  • ai ≠ bi
  • There are no duplicate edges.

Visualization

Tap to expand
Divide Nodes Into Maximum Groups INPUT Graph Structure (n=6 nodes) 1 2 3 4 5 6 n = 6 edges = [[1,2],[1,3], [2,4],[4,5],[4,6]] ALGORITHM (BFS) 1 Check Bipartiteness BFS to detect odd cycles If odd cycle: return -1 2 Find Components Identify all connected components in graph 3 BFS from Each Node Find max depth from each starting node 4 Sum Max Depths Add best depth per component for result BFS Level Assignment 3 L1 1 L2 2 L3 4 L4 5 6 FINAL RESULT Optimal Group Assignment Group 1: 3 Group 2: 1 Group 3: 2 Group 4: 4 5 6 Output: 4 Max Groups OK - Valid Grouping! Key Insight: Adjacent nodes must be in groups that differ by exactly 1. This requires a bipartite graph (no odd cycles). BFS from each node finds the maximum depth (levels) achievable. For disconnected components, we sum their individual maximum depths since they can be assigned to different group ranges independently. TutorialsPoint - Divide Nodes Into the Maximum Number of Groups | BFS Approach
Asked in
Google 12 Meta 8
8.9K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen