search
HomeBackend DevelopmentPHP TutorialDivide Nodes Into the Maximum Number of Groups

2493. Divide Nodes Into the Maximum Number of Groups

Difficulty: Hard

Topics: Breadth-First Search, Union Find, Graph

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.

Example 1:

Divide Nodes Into the Maximum Number of Groups

  • Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]
  • Output: 4
  • Explanation: As shown in the image we:
    • Add node 5 to the first group.
    • Add node 1 to the second group.
    • Add nodes 2 and 4 to the third group.
    • Add nodes 3 and 6 to the fourth group.
    • We can see that every edge is satisfied.
    • It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.

Example 2:

  • Input: n = 3, edges = [[1,2],[2,3],[3,1]]
  • Output: -1
  • Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.
    • It can be shown that no grouping is possible.

Constraints:

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

Hint:

  1. If the graph is not bipartite, it is not possible to group the nodes.
  2. Notice that we can solve the problem for each connected component independently, and the final answer will be just the sum of the maximum number of groups in each component.
  3. Finally, to solve the problem for each connected component, we can notice that if for some node v we fix its position to be in the leftmost group, then we can also evaluate the position of every other node. That position is the depth of the node in a bfs tree after rooting at node v.

Solution:

The problem, "Divide Nodes Into the Maximum Number of Groups", involves determining the maximum number of groups into which the nodes of an undirected graph can be divided, such that:

  1. Each node belongs to exactly one group.
  2. Adjacent nodes are in groups whose indices differ by exactly 1. If the graph is not bipartite, grouping is impossible, and the function must return -1.

Key Points

  • Graph Properties: The graph may be disconnected.
  • Validation: For each connected component, check if it is bipartite. If not, return -1.
  • Bipartite Nature: The solution involves BFS to validate bipartiteness.
  • Union-Find: Useful for grouping connected components efficiently.

Approach

  1. Preprocessing:

    • Represent the graph using an adjacency list.
    • Use Union-Find to identify connected components.
  2. BFS to Validate Bipartiteness:

    • For each connected component, use BFS to determine if it is bipartite.
    • If it is not bipartite, return -1.
  3. Calculate Group Count:

    • For each connected component, use BFS to determine the maximum depth, representing the maximum number of groups.
  4. Combine Results:

    • Sum the maximum group counts of all bipartite components.

Plan

  1. Construct the graph as an adjacency list.
  2. Use Union-Find to group connected components.
  3. For each node in the graph:
    • Use BFS to check if the graph is bipartite and calculate the maximum depth of that component.
  4. Return the sum of the depths of all components as the result. If any component is not bipartite, return -1.

Let's implement this solution in PHP: 2493. Divide Nodes Into the Maximum Number of Groups

<?php /**
 * @param Integer $n
 * @param Integer[][] $edges
 * @return Integer
 */
function magnificentSets($n, $edges) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

/**
 * @param $graph
 * @param $u
 * @return int
 */
private function bfs($graph, $u) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

class UnionFind {
    /**
     * @var array
     */
    private $id;
    /**
     * @var array
     */
    private $rank;

    /**
     * @param $n
     */
    public function __construct($n) {
       ...
       ...
       ...
       /**
        * go to ./solution.php
        */
    }

    /**
     * @param $u
     * @param $v
     * @return void
     */
    public function unionByRank($u, $v) {
       ...
       ...
       ...
       /**
        * go to ./solution.php
        */
    }

    /**
     * @param $u
     * @return mixed
     */
    public function find($u) {
       ...
       ...
       ...
       /**
        * go to ./solution.php
        */
    }
}


// Example usage:
$n = 6;
$edges = [[1,2], [1,4], [1,5], [2,6], [2,3], [4,6]];
echo maxGroups($n, $edges); // Output: 4

$n = 3;
$edges = [[1,2], [2,3], [3,1]];
echo maxGroups($n, $edges); // Output: -1
?>

Explanation:

1. Union-Find Class

The Union-Find (Disjoint Set Union) structure groups nodes into connected components and performs two main tasks:

  • Find: Identify the root of a node's connected component.
  • Union: Merge two connected components based on rank.

2. BFS for Bipartite Check and Depth Calculation

  • Bipartite Validation: Using BFS, assign alternating "colors" to nodes. If adjacent nodes share the same color, the graph is not bipartite.
  • Depth Calculation: Measure the depth of the BFS tree to determine the maximum number of groups.

3. Combine Results

  • Calculate the maximum depth for each connected component.
  • Add the depths for all components to determine the result.

Example Walkthrough

Example 1

Input:

$n = 6;  
$edges = [[1,2], [1,4], [1,5], [2,6], [2,3], [4,6]];

Steps:

  1. Construct adjacency list:
   1 -> [2, 4, 5]
   2 -> [1, 3, 6]
   3 -> [2]
   4 -> [1, 6]
   5 -> [1]
   6 -> [2, 4]
  1. Use BFS on connected components:
    • Component 1: Bipartite. Max depth = 4.
  2. Sum depths across all components: 4.

Output: 4

Example 2

Input:

$n = 3;  
$edges = [[1,2], [2,3], [3,1]];

Steps:

  1. Construct adjacency list:
   1 -> [2, 3]
   2 -> [1, 3]
   3 -> [1, 2]
  1. Use BFS:
    • Component 1: Not bipartite.

Output: -1

Time Complexity

  • Graph Construction: O(E), where E is the number of edges.
  • Union-Find: O(α(N)), where N is the number of nodes (almost constant due to path compression).
  • BFS: O(V E), where V is the number of vertices. Overall Complexity: O(N E)

Output for Examples

$n = 6;
$edges = [[1,2], [1,4], [1,5], [2,6], [2,3], [4,6]];
echo magnificentSets($n, $edges); // Output: 4

$n = 3;
$edges = [[1,2], [2,3], [3,1]];
echo magnificentSets($n, $edges); // Output: -1

This approach efficiently handles the grouping problem by leveraging BFS for bipartiteness checks and depth calculations while utilizing Union-Find to simplify component management. The solution handles both connected and disconnected graphs.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Divide Nodes Into the Maximum Number of Groups. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)