Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Check for Possible Bipartition
Next article icon

Check for Possible Bipartition

Last Updated : 11 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++
#include <iostream> #include <vector> #include <queue>  using namespace std;  bool possibleBipartition(int n, vector<vector<int>>& dislikes) {     // Create the adjacency list for the graph     vector<vector<int>> graph(n + 1);     for (const auto& pair : dislikes) {         graph[pair[0]].push_back(pair[1]);         graph[pair[1]].push_back(pair[0]);     }      // Color array, -1 means uncolored     vector<int> color(n + 1, -1);      // Use BFS to try to color the graph     for (int i = 1; i <= n; ++i) {         if (color[i] == -1) {             queue<int> q;             q.push(i);             color[i] = 0; // Assign the first color              while (!q.empty()) {                 int node = q.front();                 q.pop();                  for (int neighbor : graph[node]) {                     if (color[neighbor] == -1) {                         // Assign opposite color to the neighbor                         color[neighbor] = 1 - color[node];                         q.push(neighbor);                     } else if (color[neighbor] == color[node]) {                         // Conflict found                         return false;                     }                 }             }         }     }      return true; }  // Driver code int main() {     vector<vector<int>> dislikes1 = {{1, 2}, {1, 3}, {2, 4}};     cout << (possibleBipartition(4, dislikes1) ? "true" : "false") << endl;      return 0; } 

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.



Next Article
Check for Possible Bipartition

K

krishna_g
Improve
Article Tags :
  • Graph
  • DSA
  • Uber
  • Interview-Questions
Practice Tags :
  • Uber
  • Graph

Similar Reads

    Check for Amicable Pair
    Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. Examples: Input : x = 220, y = 284 Output : Yes Proper divisors of 220 are 1
    7 min read
    Check if a given graph is Bipartite using DFS
    Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i
    9 min read
    Check if two nodes in a Binary Tree are siblings
    Given a binary tree and an array nodes[] of two nodes, the task is to check if the nodes are siblings of each other.Two nodes are considered siblings if:They are present at the same level of the tree.They share the same parent.Return "Yes" if they nodes are siblings else "No".Examples: Input : nodes
    5 min read
    Divide given Graph into Bipartite sets
    Given a graph G(V, E), divide it into two sets such that no two vertices in a set are connected directly. If not possible print "Not Possible". Examples: Input: V = 7, E = 6, Edge = {{1, 2}, {2, 3}, {3, 4}, {3, 6}, {5, 6}, {6, 7}}Output: 7 5 1 3 6 2 4 Explanation: node {7, 5, 1, 3} are not connected
    10 min read
    Bipartite Graphs in Python
    Bipartite graphs are a special type of graph where the nodes can be divided into two distinct sets, with no edges connecting nodes within the same set. Every edge connects a node from the first set to a node in the second set. What is a Bipartite Graph?A graph where the nodes can be divided into two
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences