Bipartite graph

Graphs Cycles Hard
  • Fun Fact: The problem at the heart of bipartite graph detection is used heavily in computer sciences, especially in network and social media applications
  • One real-world example is in designing matchmaking systems in multiplayer video games
  • In these games, players are sometimes seen as two distinct sets - for example, team A and team B - and we need to ensure each player in team A has a corresponding match in team B
  • Hence, the problem of partitioning the players into compatible teams turns out to be checking for a bipartite graph!

Given an undirected graph with V vertices labeled from 0 to V-1. The graph is represented using an adjacency list where adj[i] lists all nodes connected to node. Determine if the graph is bipartite or not.


A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.

Examples:

Input: V=4, adj = [[1,3],[0,2],[1,3],[0,2]]

Output: True

Explanation: The given graph is bipartite since, we can partition the nodes into two sets: {0, 2} and {1, 3}.

Input: V=4, adj = [[1,2,3],[0,2],[0,1,3],[0,2]]

Output: False

Explanation: The graph is not bipartite. If we attempt to partition the nodes into two sets, we encounter an edge that connects two nodes within the same set, which violates the bipartite property.

Input: V=5, adj = [[1,3],[0,2],[1,4],[0,4],[2,3]]

Constraints

  • E=number of edges
  • 1 ≤ V, E ≤ 104

Hints

  • "Use BFS to color nodes alternately (like a checkerboard pattern). If a node is already colored with the same color as its adjacent node, the graph is not bipartite."
  • "Recursively assign alternating colors to adjacent nodes. If any conflict is found, return False."

Company Tags

Siemens Healthineers Unity Technologies Zomato Intel Broadcom NVIDIA Roblox Texas Instruments IBM ARM MongoDB Etsy Lyft Pinterest Alibaba Twilio Shopify PayPal KPMG Zoho Target McKinsey & Company Boston Consulting Group Wayfair Byju's Google Microsoft Amazon Meta Apple Netflix Adobe