HardBreadth-First SearchUnion FindGraph

1 approach, code in every language

Problem description

You are given a positive integer n representing nodes numbered from 1 to n, and an undirected graph given by edges where edges[i] = [ai, bi] connects nodes ai and bi.

You must place each node into one of several numbered groups (groups start at 1) so that for every edge [ai, bi], the two endpoints land in groups whose numbers differ by exactly one. Not every group number needs to be used, but the assignment must respect this adjacency rule for all edges.

Return the maximum number of groups into which the nodes can be divided. If no valid assignment exists, return -1.

Example 1

Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]

Output: 4

Assigning groups as node 5 -> 1, nodes 1 and 6 -> 2, nodes 2 and 4 -> 3, node 3 -> 4 keeps every edge between consecutively numbered groups, using 4 groups in total.

Example 2

Input: n = 3, edges = [[1,2],[2,3],[3,1]]

Output: -1

The three nodes form an odd cycle (a triangle), which is not bipartite, so no valid group layering exists.

Constraints

  • 1 <= n <= 500
  • 1 <= edges.length <= 10^4
  • edges[i].length == 2
  • 1 <= ai, bi <= n
  • ai != bi
  • There is at most one edge between any pair of vertices

After the pattern

Now solve one you haven't seen.

Stacking Relay Masts Into Tiers is our own problem on the technique behind Divide Nodes Into the Maximum Number of Groups: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free