HardBreadth-First SearchUnion FindGraph

Divide Nodes Into the Maximum Number of Groups

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now