VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-for-possible-bipartition/

⇱ Check for Possible Bipartition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for Possible Bipartition

Last Updated : 23 Jul, 2025

Given a group of n people labeled from 1 to n, the task is to split them into two groups of any size such that no two people who dislike each other are in the same group. The input consists of the integer n and an array dislikes[] where each element [ai, bi] indicates that the person labeled ai dislikes the person labeled bi. The task is to return true if it is possible to split the people into two groups in this way, and false otherwise.

Examples:

Input: n = 4, dislikes = [[1, 2], [1, 3], [2, 4]]
Output: true
Explanation: The first group can have [1, 4], and the second group can have [2, 3].

Input: n = 3, dislikes = [[1, 2], [1, 3], [2, 3]]
Output: false
Explanation: We need at least 3 groups to divide them because person 1 dislikes both 2 and 3, and person 2 and 3 dislike each other.

Approach:

The problem can be viewed as a graph coloring problem where each person represents a node and each dislike pair represents an edge. The goal is to determine if the graph can be bipartite, which means we can color the graph using two colors such that no two adjacent nodes share the same color.

Step by Step Approach:

  1. Graph Representation:
    • Represent the graph using an adjacency list where each person is a node, and each dislike pair is an undirected edge.
  2. Initialization:
    • Create a color array to store the color (group) of each person, initialized to -1 (indicating uncolored).
  3. Bipartite Check:
    • Use a BFS or DFS approach to try coloring the graph. Start from each uncolored node, assign a color, and attempt to color all connected nodes with the opposite color.
    • If a conflict is found (i.e., two adjacent nodes have the same color), return false.
    • If all nodes can be successfully colored, return true.

Below is the implementation of the above approach:


Output
true

Time Complexity: O(n+m), where n is the number of people (nodes) and m is the number of dislike pairs (edges). This is because we traverse each node and edge once.
Auxiliary Space: O(n+m), due to the storage used for the adjacency list and the color array.


Comment
Article Tags: