Skip to contentKEEP THE CRAFTTHE SANCTUARY

Bipartite Check

Propagate opposite colors across every undirected component. Treat color zero as assigned, reject same-color edges including self-loops, and connect a conflict to an odd cycle rather than to any cycle.

1 practice exercise1 interview problem

Recognize it when Vertices must be split into two groups with no edge inside a group.

Checking your account…

Bipartite Check Code Labs

Assign Opposite Colors Across Edges

A graph is bipartite exactly when vertices can receive two colors so every edge joins opposite colors. BFS or DFS propagates the forced opposite color.

Start Every Disconnected Component

An uncolored vertex seeds a new component with either color. Checking only one source can miss an odd cycle elsewhere in the graph.

Trace Bipartite Coloring

Reference
from collections import deque

def coloring_trace(adjacency):
    colors=[-1]*len(adjacency);trace=[]
    for start in range(len(adjacency)):
        if colors[start]!=-1:continue
        colors[start]=0;trace.append([start,0]);queue=deque([start])
        while queue:
            node=queue.popleft()
            for neighbor in adjacency[node]:
                if colors[neighbor]==-1:colors[neighbor]=1-colors[node];trace.append([neighbor,colors[neighbor]]);queue.append(neighbor)
    return trace
Practice

Implement coloring_trace(adjacency). Return [node,color] in BFS assignment order across all components, colors 0 and 1. adjacency represents an undirected graph with symmetric neighbor entries and valid vertex indices.

Public tests

  • Seed every disconnected component

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Bipartite Coloring

from collections import deque

def coloring_trace(adjacency):
    colors=[-1]*len(adjacency);trace=[]
    for start in range(len(adjacency)):
        if colors[start]!=-1:continue
        colors[start]=0;trace.append([start,0]);queue=deque([start])
        while queue:
            node=queue.popleft()
            for neighbor in adjacency[node]:
                if colors[neighbor]==-1:colors[neighbor]=1-colors[node];trace.append([neighbor,colors[neighbor]]);queue.append(neighbor)
    return trace

Seed a Separate Component after the First Queue Empties

Predict the existing assignment trace for two disconnected edges and one isolated vertex. Its output records the forced colors; the separate checker Lab is the one that rejects conflicting edges.

Step Executed statement State Why
Seed first component colors[start]=0;trace.append([start,0]);queue=deque([start]) node 0 assigned 0 Either initial color is valid for a new component.
Propagate colors[neighbor]=1-colors[node];trace.append([neighbor,colors[neighbor]]);queue.append(neighbor) node 1 assigned 1 The edge forces the opposite color.
Skip assigned start if colors[start]!=-1:continue start 1 skipped Assigned zero and one are both already handled.
Seed next component colors[start]=0;trace.append([start,0]);queue=deque([start]) node 2 gets 0; queue=[2] Disconnected components have independent color orientation.
Propagate second component node=queue.popleft();colors[neighbor]=1-colors[node];trace.append([neighbor,colors[neighbor]]);queue.append(neighbor) after node 2 iteration: node 3 gets 1 The actual neighbor assignment, rather than seeding alone, forces the opposite color across edge 2-3.
Isolated vertex colors[start]=0;trace.append([start,0]);queue=deque([start]) node 4 gets 0 Every vertex participates, even with no outgoing adjacency entries.
Print Output
print(coloring_trace([[1], [0], [3], [2], []])) [[0, 0], [1, 1], [2, 0], [3, 1], [4, 0]]

Try reasoning about a four-cycle versus a triangle: the first can alternate consistently, while the last edge of the triangle joins equal parity. Returning a Boolean does not reconstruct that witness, which requires extra parent tracking.

Reject Same Color Neighbors

For each edge, assign an unseen neighbor the opposite color or reject an already colored neighbor that matches the current color. A self-loop immediately violates the condition.

Check Bipartite Graph

Reference
from collections import deque

def is_bipartite(adjacency):
    colors=[-1]*len(adjacency)
    for start in range(len(adjacency)):
        if colors[start]!=-1:continue
        colors[start]=0;queue=deque([start])
        while queue:
            node=queue.popleft()
            for neighbor in adjacency[node]:
                if colors[neighbor]==-1:colors[neighbor]=1-colors[node];queue.append(neighbor)
                elif colors[neighbor]==colors[node]:return False
    return True
Practice

Implement is_bipartite(adjacency). Return whether every edge connects opposite colors across all components. adjacency represents an undirected graph with symmetric neighbor entries and valid vertex indices.

Public tests

  • Reject odd cycles and self loops

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Check Bipartite Graph

from collections import deque

def is_bipartite(adjacency):
    colors=[-1]*len(adjacency)
    for start in range(len(adjacency)):
        if colors[start]!=-1:continue
        colors[start]=0;queue=deque([start])
        while queue:
            node=queue.popleft()
            for neighbor in adjacency[node]:
                if colors[neighbor]==-1:colors[neighbor]=1-colors[node];queue.append(neighbor)
                elif colors[neighbor]==colors[node]:return False
    return True

Recover the Odd Cycle Meaning

A same-color edge connects vertices at equal parity from the component seed, closing an odd-length cycle. Parent tracking can reconstruct that witness when the prompt requires more than a Boolean.

Explain It in an Interview

Say: “Color represents path-length parity from a component seed. Every edge must flip parity; a same-color edge proves an odd cycle.” State disconnected traversal and O(V + E) time and space.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Bipartite Check proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Two-color traversalO(V + E)O(V + E)Each vertex is assigned once; every adjacency entry is checked.

Space

O(V) colors and queue beyond input adjacency, plus O(V) assignment trace.

Assumptions

  • Use deque.popleft for constant-time FIFO removals.
  • A valid coloring can swap both colors within a component; vertex labels do not fix color.

Invariants Worth Saying Aloud

  1. Every discovered edge either assigns the opposite color or checks that relation.
  2. Color -1 means unassigned; 0 and 1 are both assigned colors.
  3. A same-color edge contradicts parity and yields an odd-cycle witness.

When To Use Or Avoid Bipartite Check

Use It When

  • Use BFS or DFS two-coloring to test a complete undirected graph.
  • Seed each uncolored disconnected component independently.

Choose Another Tool When

  • An even cycle is bipartite; cycle existence alone is not a rejection criterion.
  • This undirected parity proof does not justify one-way reachability coloring on arbitrary asymmetric adjacency.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using truthiness to test whether a color is assigned

Assigned color 0 is falsy. if not colors[node] incorrectly treats it as unassigned.

Prevent it: Compare the -1 sentinel explicitly.

Avoid

unassigned = not colors[node]

Use instead

unassigned = colors[node] == -1

Copying the parent color onto its neighbor

Both endpoints become 0, immediately violating the edge requirement.

Prevent it: Assign 1 - colors[node] to a newly discovered neighbor.

Avoid

colors[neighbor] = colors[node]

Use instead

colors[neighbor] = 1 - colors[node]

Skipping checks for already colored neighbors

An odd cycle may connect two already assigned color-0 nodes. Testing only unseen neighbors never rejects that conflict.

Prevent it: Check equal colors on every edge to an assigned neighbor.

Avoid

conflict = colors[neighbor] == -1

Use instead

conflict = colors[neighbor] == colors[node]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.