📖 Scenario: You are working on a social network app. You want to check if the users can be split into two groups so that no two friends are in the same group. This means the friendship connections form a bipartite graph.
🎯 Goal: Build a Rust program that checks if a given graph is bipartite using a coloring method.
📋 What You'll Learn
Create a graph using an adjacency list representation with exact edges
Add a vector to store colors of each node initialized to -1
Implement a function to check bipartite property using BFS and coloring
Print whether the graph is bipartite or not
💡 Why This Matters
🌍 Real World
Bipartite graphs are used in social networks, job assignments, and scheduling where two groups must be separated without conflicts.
💼 Career
Understanding graph algorithms like bipartite checking is important for software engineers working on network analysis, recommendation systems, and optimization problems.
Progress0 / 4 steps
1
Create the graph adjacency list
Create a variable called graph as a Vec> with 4 nodes and these edges: 0 connected to 1 and 3, 1 connected to 0 and 2, 2 connected to 1 and 3, 3 connected to 0 and 2.
DSA Rust
Hint
Use vec![vec![...], vec![...], ...] to create adjacency lists for each node.
2
Create the colors vector
Create a mutable vector called colors of type Vec with length 4, initialized with -1 for each node to represent uncolored nodes.
DSA Rust
Hint
Use vec![-1; 4] to create a vector with 4 elements all set to -1.
3
Implement the bipartite check function
Write a function called is_bipartite that takes graph: &Vec> and colors: &mut Vec and returns bool. Use a BFS approach starting from each uncolored node, assign color 0, then assign opposite colors to neighbors. If a conflict is found, return false. Otherwise, return true.
DSA Rust
Hint
Use a queue (VecDeque) for BFS. Color the start node 0, then assign neighbors the opposite color. If a neighbor has the same color, return false.
4
Print the bipartite check result
Call the function is_bipartite with &graph and &mut colors. Print "Graph is bipartite" if it returns true, otherwise print "Graph is not bipartite".
DSA Rust
Hint
Call is_bipartite(&graph, &mut colors) and print the result with println!.
Practice
(1/5)
1. What does it mean for a graph to be bipartite?
easy
A. Its vertices can be divided into two groups with no edges inside the same group
B. It has an equal number of vertices and edges
C. It contains at least one cycle of odd length
D. All vertices have the same degree
Solution
Step 1: Understand bipartite graph definition
A bipartite graph is one where vertices can be split into two sets so that no edge connects vertices within the same set.
Step 2: Check options against definition
Its vertices can be divided into two groups with no edges inside the same group matches this definition exactly. Options A, B, and D describe unrelated properties.
Final Answer:
Its vertices can be divided into two groups with no edges inside the same group -> Option A
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 graphs must have cycles
Assuming all vertices have same degree
2. Which Rust code snippet correctly declares an adjacency list for an undirected graph to check bipartiteness?
easy
A. let graph: Vec<(usize, usize)> = Vec::new();
B. let graph: Vec<usize> = vec![0; n];
C. let graph: HashMap = HashMap::new();
D. let graph: Vec = vec![vec![]; n];
Solution
Step 1: Identify adjacency list type
An adjacency list for a graph is usually a vector of vectors, where each inner vector holds neighbors of a vertex.
Step 2: Match code snippet to adjacency list
let graph: Vec = vec![vec![]; n]; declares a vector of vectors of usize, initialized with empty vectors for each vertex, which is correct. Options A, B, and C do not represent adjacency lists properly.
Final Answer:
let graph: Vec = vec![vec![]; n]; -> Option D
Quick Check:
Adjacency list = Vec of Vecs [OK]
Hint: Adjacency list is Vec in Rust [OK]
Common Mistakes:
Using Vec<usize> instead of Vec
Using HashMap with wrong types
Using tuple vector which is edge list, not adjacency list
3. Given the following Rust code snippet to check bipartiteness, what is the output?
let graph = vec![
vec![1, 3],
vec![0, 2],
vec![1, 3],
vec![0, 2],
];
fn is_bipartite(graph: &Vec) -> bool {
let n = graph.len();
let mut colors = vec![-1; n];
for i in 0..n {
if colors[i] == -1 {
let mut stack = vec![i];
colors[i] = 0;
while let Some(u) = stack.pop() {
for &v in &graph[u] {
if colors[v] == -1 {
colors[v] = 1 - colors[u];
stack.push(v);
} else if colors[v] == colors[u] {
return false;
}
}
}
}
}
true
}
println!("{}", is_bipartite(&graph));
medium
A. true
B. false
C. Compilation error
D. Runtime panic
Solution
Step 1: Analyze graph structure
The graph has 4 vertices with edges forming a square (0-1-2-3-0). This is an even cycle, which is bipartite.
Step 2: Trace DFS coloring
The code colors vertex 0 as 0, then neighbors 1 and 3 as 1, then neighbors 2 as 0. No conflicts occur, so it returns true.
Final Answer:
true -> Option A
Quick Check:
Even cycle graph is bipartite = true [OK]
Hint: Even cycles are bipartite, so output is true [OK]
Common Mistakes:
Thinking all cycles are non-bipartite
Confusing stack usage with queue
Missing color conflict check
4. The following Rust code attempts to check if a graph is bipartite but has a bug. What is the bug?
fn is_bipartite(graph: &Vec) -> bool {
let n = graph.len();
let mut colors = vec![-1; n];
for i in 0..n {
if colors[i] == -1 {
let mut stack = vec![i];
colors[i] = 0;
while let Some(u) = stack.pop() {
for &v in &graph[u] {
if colors[v] == -1 {
colors[v] = colors[u]; // Bug here
stack.push(v);
} else if colors[v] == colors[u] {
return false;
}
}
}
}
}
true
}
medium
A. Stack is used instead of queue, causing infinite loop
B. Colors assigned to neighbors are same as current vertex, causing wrong bipartite check
C. colors vector is initialized with zeros instead of -1
D. Graph parameter should be mutable
Solution
Step 1: Identify color assignment bug
The code assigns neighbors the same color as current vertex, which breaks bipartite property requiring opposite colors.
Step 2: Understand impact on bipartite check
This causes false negatives or positives because neighbors must have opposite colors, so the check fails.
Final Answer:
Colors assigned to neighbors are same as current vertex, causing wrong bipartite check -> Option B
Quick Check:
Neighbors must have opposite colors [OK]
Hint: Neighbors must get opposite color, not same [OK]
Common Mistakes:
Assigning same color to neighbors
Confusing stack and queue usage
Initializing colors incorrectly
5. You have a graph with vertices 0 to 5 and edges: (0-1), (1-2), (2-3), (3-0), (3-4), (4-5). Which of the following statements is true about its bipartiteness?
hard
A. The graph is not bipartite because it contains an odd cycle (3-4-5)
B. The graph is not bipartite because it contains an even cycle (0-1-2-3)
C. The graph is bipartite because it contains no odd cycles
D. The graph is bipartite because all vertices have degree 2 or less
Solution
Step 1: Identify cycles in the graph
The graph has a cycle 0-1-2-3-0 which is length 4 (even). The path 3-4-5 is a chain, not a cycle.
Step 2: Check bipartite condition
Graphs with no odd cycles are bipartite. Since the only cycle is even, the graph is bipartite.
Final Answer:
The graph is bipartite because it contains no odd cycles -> Option C
Quick Check:
No odd cycles means bipartite [OK]
Hint: Check for odd cycles; none means bipartite [OK]
Common Mistakes:
Mistaking chains for cycles
Thinking even cycles break bipartiteness
Assuming degree affects bipartiteness
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.