DFS, BFS & Graph Traversal · 15 min · free lesson

Challenge: Bipartite Coloring

Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored.

Core idea

An edge joins two vertices assigned the same color. Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Assign opposite colors across every edge and reject any edge whose endpoints match.

O(V+E) time · O(V) space25 execution steps
main · before line 25Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputn=3 edges=(0,1),(1,2),(2,0)

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 25
fn bipartite(graph: &[Vec<usize>]) -> bool {
    let mut color = vec![None; graph.len()];
    for start in 0..graph.len() {
        if color[start].is_some() {
            continue;
        }
        color[start] = Some(false);
        let mut queue = std::collections::VecDeque::from([start]);
        while let Some(v) = queue.pop_front() {
            for &u in &graph[v] {
                if color[u] == color[v] {
                    return false;
                }
                if color[u].is_none() {
                    color[u] = Some(!color[v].unwrap());
                    queue.push_back(u);
                }
            }
        }
    }
    true
}
 
fn main() {
    let result = bipartite(&[vec![1, 2], vec![0, 2], vec![0, 1]]).to_string();
    println!("{result}");
}

Try your own version

Change the independent fixture `n=3 edges=(0,1),(1,2),(2,0)` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `n=4 edges=(0,1),(1,2),(2,3),(3,0)`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel DFS, BFS & Graph Traversal infographic; panel 1 illustrates Bipartite Coloring.
Bipartite Coloring: follow panel 1 to see the operation, then trace this lesson's example.

Understand it

An edge joins two vertices assigned the same color. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input n=3 edges=(0,1),(1,2),(2,0), the worked program returns false. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input n=4 edges=(0,1),(1,2),(2,3),(3,0); predict that result before opening the answer reveal. The precise contract is: Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored. On input n=4 edges=(0,1),(1,2),(2,3),(3,0), predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Assign opposite colors across every edge and reject any edge whose endpoints match. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A graph method needs an explicit vertex-and-edge representation. For traversal, define when a vertex becomes seen: on insertion into the frontier or on removal. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(V+E) time · O(V) space; explain which operation dominates it and how many times the input can trigger that operation. Test an isolated vertex, a cycle, duplicate edges, and a graph whose starting vertex reaches only one component. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Assign opposite colors across every edge and reject any edge whose endpoints match.

When to use it: two-team constraints and odd-cycle detection

Complexity: O(V+E) time · O(V) space

Input: n=4 edges=(0,1),(1,2),(2,3),(3,0)

Read the code

fn bipartite(graph: &[Vec<usize>]) -> bool {
    let mut color = vec![None; graph.len()];
    for start in 0..graph.len() {
        if color[start].is_some() {
            continue;
        }
        color[start] = Some(false);
        let mut queue = std::collections::VecDeque::from([start]);
        while let Some(v) = queue.pop_front() {
            for &u in &graph[v] {
                if color[u] == color[v] {
                    return false;
                }
                if color[u].is_none() {
                    color[u] = Some(!color[v].unwrap());
                    queue.push_back(u);
                }
            }
        }
    }
    true
}

fn main() {
    let result = bipartite(&[vec![1, 2], vec![0, 2], vec![0, 1]]).to_string();
    println!("{result}");
}

Complete std-only bipartite-coloring program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement bipartite-coloring")
}

Try it

Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored.

What success looks like: The private harness prints PASS bipartite-coloring. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for bipartite-coloring: with input n=4 edges=(0,1),(0,2),(0,3), what result should solve return?

Reveal the answer
  1. true
  2. false
  3. The valid input necessarily panics

For this input the result is true. An edge joins two vertices assigned the same color. Compare this independent fixture with the worked trace: A four-cycle alternates colors and succeeds. A triangle forces the final edge to join equal colors, so it fails. Start coloring again in each disconnected component; an isolated vertex poses no contradiction.

Go deeper

Common misconception: “A vertex has degree greater than two”

An edge joins two vertices assigned the same color. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: An edge joins two vertices assigned the same color. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses n=3 edges=(0,1),(1,2),(2,0) and computes false. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For n=3 edges=(0,1),(1,2),(2,0), the independently calculated result is false. The complexity discussion uses O(V+E) time · O(V) space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture n=3 edges=(0,1),(1,2),(2,0) in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge n=4 edges=(0,1),(1,2),(2,3),(3,0).

Connections

  • Bipartite Coloring: When to Use It: two-team constraints and odd-cycle detection
  • Undirected Cycle Detection: Mental Model: During traversal ignore the edge back to the parent; any other seen neighbor closes a cycle.
Reveal the Algorithm Atlas answer

true

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Bipartite Coloring (courseId "algorithms", lessonId "algorithm.bipartite-coloring.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.bipartite-coloring.challenge
Goal: An edge joins two vertices assigned the same color. Parse n and undirected edges; the graph may be disconnected. Return whether it can be two-colored.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.bipartite-coloring.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.