Browse Curriculum

Bipartite Graph

Learn how to determine if a graph can be bipartite using 2-Coloring (BFS/DFS). Essential for matching problems and cycle analysis.

ABCD

Ready to start

Speed
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Intuition

Can you divide a group of people into two teams such that no two teammates are friends?

If you can, the network of friendships is a Bipartite Graph.

We solve this by trying to color the graph with just two colors (e.g., Red and Blue).

Concept

  • Bipartite Graph: A graph where vertices can be split into two sets, U and V, such that every edge connects a vertex in U to one in V.
  • 2-Coloring: If we can color every node either Red or Blue such that no two connected nodes have the same color, the graph is bipartite.
  • Odd Cycle Property: A graph is bipartite if and only if it contains no odd cycles.

How it Works

Algorithm (BFS 2-Coloring):
  1. Initialize an array color with 0 (uncolored) for all nodes.
  2. Iterate through all nodes. If uncolored, start BFS:
  3. Color the start node 1 (Red).
  4. For each neighbor:
    • If uncolored: Color it with the opposite color (2 if current is 1, 1 if current is 2) and push to queue.
    • If already colored with same color: Conflict found! Return false.
  5. If traversal completes without conflict, return true.

Step-by-Step Breakdown

Watch the visualization:

  • Red Node: Assigned to Set A.
  • Blue Node: Assigned to Set B.
  • Conflict (Dark Red): Found a neighbor with the same color. Graph is NOT bipartite.

When to Use

Use Bipartite Check when:

  • Allocating resources into two independent sets.
  • Stable Marriage problem and other matching algorithms.
  • Detecting odd cycles in a graph.

When NOT to Use

  • Directed Graphs: The definition applies to undirected graphs (though similar concepts exist for directed acyclicity).

How to Identify

"Can we split into two groups?", "Is there an odd cycle?", "2-Coloring possible?".

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep