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 GroupsInput Graph123n=3, edges=[[1,2],[1,3],[2,3]]Constraint: |group[u] - group[v]| = 1G1G2G?Triangle → Impossible!Valid ExampleG1G2|2-1| = 1 ✓Max Groups = 2Result: Return maximum groups possible or -1 if impossible
Understanding the Visualization
1
Input Graph
Undirected graph with nodes and edges
2
Apply Constraint
Adjacent nodes must be in consecutive groups
3
Find Maximum
Return highest group number possible
Key Takeaway
🎯 Key Insight: The constraint creates bipartite structure - find diameter of each component
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