Bird
Raised Fist0
DSA C#programming

Bipartite Graph Check in DSA C#

Choose your learning style10 modes available
Mental Model
A bipartite graph can be split into two groups where no nodes inside the same group connect to each other.
Analogy: Imagine two teams playing a game where players only pass the ball to the other team, never to their own teammates.
Group A: 1 -> 3 -> 5
Group B: 2 -> 4 -> 6
Edges only go between groups, never inside one group.
Dry Run Walkthrough
Input: Graph with edges: 1-2, 2-3, 3-4, 4-1
Goal: Check if the graph can be colored using two colors so that no connected nodes share the same color.
Step 1: Start coloring node 1 with color 0
Node colors: 1[0], 2[?], 3[?], 4[?]
Why: We pick a starting node and assign it a color to begin the check.
Step 2: Color node 2 with color 1 (opposite of node 1)
Node colors: 1[0], 2[1], 3[?], 4[?]
Why: Neighbors must have opposite colors to avoid same-group edges.
Step 3: Color node 3 with color 0 (opposite of node 2)
Node colors: 1[0], 2[1], 3[0], 4[?]
Why: Continue coloring neighbors with opposite colors.
Step 4: Color node 4 with color 1 (opposite of node 3)
Node colors: 1[0], 2[1], 3[0], 4[1]
Why: All nodes colored without conflict so far.
Step 5: Check edge 4-1: both nodes have colors 1 and 0, no conflict
Node colors: 1[0], 2[1], 3[0], 4[1]
Why: Edges connect nodes of different colors, so graph is bipartite.
Result:
Node colors: 1[0], 2[1], 3[0], 4[1]
Graph is bipartite: true
Annotated Code
DSA C#
using System;
using System.Collections.Generic;

class Graph {
    private readonly int V;
    private readonly List<int>[] adj;

    public Graph(int vertices) {
        V = vertices;
        adj = new List<int>[V];
        for (int i = 0; i < V; i++) {
            adj[i] = new List<int>();
        }
    }

    public void AddEdge(int u, int v) {
        adj[u].Add(v);
        adj[v].Add(u);
    }

    public bool IsBipartite() {
        int[] colors = new int[V];
        for (int i = 0; i < V; i++) {
            colors[i] = -1; // -1 means uncolored
        }

        for (int i = 0; i < V; i++) {
            if (colors[i] == -1) {
                if (!BFSCheck(i, colors)) {
                    return false;
                }
            }
        }
        return true;
    }

    private bool BFSCheck(int start, int[] colors) {
        Queue<int> queue = new Queue<int>();
        colors[start] = 0; // start coloring with 0
        queue.Enqueue(start);

        while (queue.Count > 0) {
            int u = queue.Dequeue();
            foreach (int v in adj[u]) {
                if (colors[v] == -1) {
                    colors[v] = 1 - colors[u]; // opposite color
                    queue.Enqueue(v);
                } else if (colors[v] == colors[u]) {
                    return false; // same color neighbor found
                }
            }
        }
        return true;
    }
}

class Program {
    static void Main() {
        Graph g = new Graph(4);
        g.AddEdge(0, 1);
        g.AddEdge(1, 2);
        g.AddEdge(2, 3);
        g.AddEdge(3, 0);

        bool result = g.IsBipartite();
        Console.WriteLine("Graph is bipartite: " + result.ToString().ToLower());
    }
}
colors[i] = -1; // -1 means uncolored
Initialize all nodes as uncolored
if (colors[i] == -1) { if (!BFSCheck(i, colors)) { return false; } }
Start BFS from uncolored nodes to cover disconnected graphs
colors[start] = 0; // start coloring with 0
Assign first color to start node
colors[v] = 1 - colors[u]; // opposite color
Assign opposite color to neighbor
else if (colors[v] == colors[u]) { return false; }
Detect conflict if neighbor has same color
OutputSuccess
Graph is bipartite: true
Complexity Analysis
Time: O(V + E) because we visit each vertex and edge once during BFS
Space: O(V) for the colors array and BFS queue
vs Alternative: Compared to DFS, BFS is equally efficient here; naive checking all pairs would be O(V^2)
Edge Cases
Empty graph (no vertices)
Returns true since no edges exist to violate bipartite property
DSA C#
for (int i = 0; i < V; i++) { if (colors[i] == -1) { ... } }
Graph with one vertex and no edges
Returns true as single node can be colored any color
DSA C#
colors[start] = 0; // start coloring with 0
Graph with odd cycle (e.g., triangle)
Returns false because odd cycles cannot be bipartite
DSA C#
else if (colors[v] == colors[u]) { return false; }
When to Use This Pattern
When you need to split nodes into two groups with no internal edges, use bipartite check with BFS or DFS coloring to detect conflicts.
Common Mistakes
Mistake: Not checking all disconnected components of the graph
Fix: Run BFS/DFS from every uncolored node to cover all components
Mistake: Assigning the same color to neighbors without checking
Fix: Always assign opposite color and check for conflicts
Summary
Checks if a graph can be divided into two groups with no edges inside the same group.
Use when you want to know if a graph is bipartite or can be 2-colored.
The key is to color neighbors with opposite colors and detect conflicts.

Practice

(1/5)
1. What does it mean for a graph to be bipartite?
easy
A. All vertices have the same degree
B. It has an equal number of vertices and edges
C. It contains at least one cycle
D. Its vertices can be divided into two groups with no edges inside the same group

Solution

  1. Step 1: Understand bipartite graph definition

    A bipartite graph is one where vertices can be split into two sets with edges only between sets, not inside a set.
  2. Step 2: Compare options with definition

    Its vertices can be divided into two groups with no edges inside the same group matches this definition exactly, while others describe unrelated properties.
  3. Final Answer:

    Its vertices can be divided into two groups with no edges inside the same group -> Option D
  4. Quick Check:

    Bipartite graph = two groups, no internal edges [OK]
Hint: Bipartite means two groups with no edges inside groups [OK]
Common Mistakes:
  • Confusing bipartite with equal vertices and edges
  • Thinking bipartite means no cycles
  • Assuming all vertices have same degree
2. Which C# data structure is best to represent a graph for bipartite check?
easy
A. List adjacency list
B. Dictionary adjacency list
C. int[,] adjacency matrix
D. HashSet<int> for vertices only

Solution

  1. Step 1: Identify graph representation needs

    We need to store edges efficiently and access neighbors quickly for bipartite check.
  2. Step 2: Evaluate options

    Dictionary allows flexible vertex keys and fast neighbor lookup, better than fixed-size arrays or sets.
  3. Final Answer:

    Dictionary adjacency list -> Option B
  4. Quick Check:

    Dictionary adjacency list = best for flexible graphs [OK]
Hint: Use Dictionary for flexible graph edges [OK]
Common Mistakes:
  • Using HashSet only stores vertices, no edges
  • Adjacency matrix wastes space for sparse graphs
  • List lacks vertex key mapping
3. What is the output of this C# code snippet checking bipartite for a graph with edges: 0-1, 1-2, 2-3, 3-0?
var graph = new Dictionary {
  {0, new List<int>{1,3}},
  {1, new List<int>{0,2}},
  {2, new List<int>{1,3}},
  {3, new List<int>{2,0}}
};
bool IsBipartite(Dictionary g) {
  var color = new Dictionary();
  foreach(var node in g.Keys) {
    if(!color.ContainsKey(node)) {
      var queue = new Queue<int>();
      queue.Enqueue(node);
      color[node] = 0;
      while(queue.Count > 0) {
        var u = queue.Dequeue();
        foreach(var v in g[u]) {
          if(!color.ContainsKey(v)) {
            color[v] = 1 - color[u];
            queue.Enqueue(v);
          } else if(color[v] == color[u]) {
            return false;
          }
        }
      }
    }
  }
  return true;
}
Console.WriteLine(IsBipartite(graph));
medium
A. True
B. False
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Analyze the graph structure

    The graph forms a cycle of length 4: 0-1-2-3-0.
  2. Step 2: Check bipartite condition on even cycle

    Even cycles are bipartite, but here the cycle is length 4 (even), so it should be bipartite. However, the code returns false if adjacent nodes have same color.
  3. Step 3: Trace coloring

    Coloring alternates 0 and 1 around the cycle, no conflict occurs, so function returns true.
  4. Final Answer:

    True -> Option A
  5. Quick Check:

    Even cycle graph is bipartite = True [OK]
Hint: Even cycles are bipartite; odd cycles are not [OK]
Common Mistakes:
  • Assuming all cycles are not bipartite
  • Confusing color assignment logic
  • Ignoring queue BFS traversal
4. Identify the bug in this bipartite check code snippet:
bool CheckBipartite(Dictionary graph) {
  var color = new Dictionary();
  foreach(var node in graph.Keys) {
    if(!color.ContainsKey(node)) {
      color[node] = 0;
      var stack = new Stack<int>();
      stack.Push(node);
      while(stack.Count > 0) {
        var u = stack.Pop();
        foreach(var v in graph[u]) {
          if(!color.ContainsKey(v)) {
            color[v] = color[u];
            stack.Push(v);
          } else if(color[v] == color[u]) {
            return false;
          }
        }
      }
    }
  }
  return true;
}
medium
A. Colors assigned to neighbors are same as current node, should be opposite
B. Stack should be replaced with queue for BFS
C. Missing initialization of color dictionary
D. No return statement for true case

Solution

  1. Step 1: Review color assignment logic

    Neighbors must have opposite colors to current node for bipartite check.
  2. Step 2: Identify incorrect assignment

    Code assigns neighbor color same as current node, causing false negatives.
  3. Final Answer:

    Colors assigned to neighbors are same as current node, should be opposite -> Option A
  4. Quick Check:

    Neighbor colors must differ [OK]
Hint: Neighbors must have opposite colors, not same [OK]
Common Mistakes:
  • Assigning same color to neighbors
  • Confusing stack vs queue (both work but BFS preferred)
  • Forgetting to initialize colors
5. Given a graph with vertices 0 to 5 and edges: 0-1, 1-2, 2-3, 3-4, 4-5, 5-0, and 1-4, is the graph bipartite? Explain why.
hard
A. Yes, because all cycles are even length
B. No, because it has a self-loop
C. No, because it contains an odd cycle including edges 1-2-3-4-1
D. Yes, because it has no cycles

Solution

  1. Step 1: Identify cycles in the graph

    The graph has a large cycle 0-1-2-3-4-5-0 (length 6, even), and with edge 1-4, cycles 1-2-3-4-1 (length 4, even) and 0-1-4-5-0 (length 4, even).
  2. Step 2: Check for odd-length cycles

    No odd-length cycles exist. A graph is bipartite if and only if it has no odd-length cycles.
  3. Final Answer:

    No, because it contains an odd cycle including edges 1-2-3-4-1 -> Option C
  4. Quick Check:

    Odd cycle means not bipartite [OK]
Hint: Check for odd cycles to decide bipartite [OK]
Common Mistakes:
  • Miscounting cycle lengths
  • Assuming any cycle means not bipartite
  • Ignoring extra edges creating odd cycles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard