Tutorialspoint
Problem
Solution
Submissions

Check if a Graph is Bipartite.

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python program that checks if a given graph is bipartite.

Example 1
  • Input: [[1, 3], [0, 2], [1, 3], [0, 2]]
  • Output: True
  • Explanation:
    • Step 1: Initialize a color array to track node colors (-1 = uncolored, 0 = first color, 1 = second color).
    • Step 2: Start DFS/BFS from each uncolored node.
    • Step 3: Assign a color to the current node and the opposite color to its neighbors.
    • Step 4: If a neighbor already has the same color as the current node, the graph is not bipartite.
    • Step 5: In this case, all nodes can be colored without conflicts, so the graph is bipartite.
Example 2
  • Input: [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]
  • Output: False
  • Explanation:
    • Step 1: Start coloring nodes using BFS/DFS.
    • Step 2: Node 0 is colored with color 0.
    • Step 3: Neighbors of node 0 (nodes 1, 2, 3) are colored with color 1.
    • Step 4: When coloring neighbors of node 1 (nodes 0, 2), we find that node 2 should have color 0.
    • Step 5: But node 2 is already colored with color 1, creating a conflict.
    • Step 6: Since there's a coloring conflict, the graph is not bipartite.
Constraints
  • 1 ≤ len(graph) ≤ 100
  • 0 ≤ graph[i][j] < len(graph)
  • The graph is undirected
  • Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges
  • Space Complexity: O(V)
GraphAlgorithmsTutorialspointIBM
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use BFS or DFS to traverse the graph.
  • Assign colors to nodes and ensure no two adjacent nodes have the same color.
  • Handle disconnected graphs by checking all components.

Steps to solve by this approach:

 Step 1: Use graph coloring with two colors (0 and 1).
 Step 2: Start with any uncolored node and assign it color 0.
 Step 3: Use DFS or BFS to color adjacent nodes with the opposite color.
 Step 4: If any adjacent nodes have the same color, the graph is not bipartite.
 Step 5: Continue until all nodes are colored or a conflict is found.
 Step 6: Return true if all nodes can be colored without conflicts, false otherwise.

Submitted Code :