learngraphtheory.org

Interactive Graph Theory Learning

Guest User

Using app without sign in

Study resources
Take graph theory beyond the screen
Instant download·Lifetime access
Algorithm Selection

Bipartite Graph Checker

Bipartite graph checker

Determines if graph can be colored with two colors

Time: O(V + E)
Space: O(V)
Use Case: Matching problems, scheduling, resource allocation
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Bipartite Check

A graph is bipartite when its vertices can be split into two groups with every edge crossing between the groups, never inside one. Checking bipartiteness is equivalent to testing whether the graph can be colored with two colors, or whether it contains no odd-length cycle.

How it works

A BFS or DFS traversal 2-colors the graph on the fly: color the start vertex, then give every discovered neighbor the opposite color. If an edge ever connects two vertices of the same color, an odd cycle exists and the graph is not bipartite. Every component must be checked. The test runs in O(V + E) time.

Applications

Bipartite structure underlies matching problems: assigning students to schools, jobs to machines, and riders to drivers. Recommender systems model users and items as the two sides of a bipartite graph. The odd-cycle characterization is a frequent interview warm-up that leads into maximum matching topics.

Pseudocode

A graph is bipartite exactly when it can be two-coloured. So the test is a traversal that colours each vertex opposite to its parent and watches for a clash.

isBipartite(graph):
    color = {} for all vertices

    for each vertex s with no color:   // every component
        color[s] = 0
        queue = [s]
        while queue is not empty:
            u = queue.pop()
            for each neighbor v of u:
                if v has no color:
                    color[v] = 1 - color[u]
                    queue.push(v)
                else if color[v] == color[u]:
                    return false      // odd cycle found

    return true

The clash is not an arbitrary failure signal, it is a proof. If two adjacent vertices receive the same colour, the tree paths from them back to their common ancestor plus the connecting edge form a cycle of odd length. Bipartite graphs are exactly the graphs with no odd cycle, so the conflict edge is a certificate you can hand back to the caller.

Worked example, step by step

Two-colour a four-cycle, then add one chord and watch the same traversal reject it.

Example graph: First a 4-cycle A-B, B-C, C-D, D-A. Then the same graph with the chord A-C added.

  1. Colour the 4-cycle from A. A gets colour 0. Its neighbours B and D get colour 1. From B, the neighbour C is uncoloured and gets colour 0. From D, the neighbour C is already coloured 0 while D is 1, which is a valid difference, so nothing conflicts.
  2. Result for the 4-cycle. Colours are A 0, B 1, C 0, D 1. The graph is bipartite, with parts {A, C} and {B, D}. Every edge runs between the two parts and none within.
  3. Add the chord A-C. A and C are both colour 0, so the chord now joins two vertices of the same part. Rerun the traversal from A: A gets 0, and its neighbours B, D and now C all get 1.
  4. The conflict surfaces. Processing B, whose colour is 1, its neighbour C also has colour 1. That is an edge inside one part, so the algorithm returns false at edge B-C.
  5. Why the chord breaks it. The chord creates the triangle A-B-C, a cycle of length 3. Odd cycles cannot be two-coloured: walking round an odd cycle alternating colours returns you to the start needing the opposite of what it already has.

The 4-cycle is bipartite with parts {A, C} and {B, D}; adding the chord A-C makes it non-bipartite, detected at edge B-C. Note the general rule this illustrates: every even cycle is bipartite and every odd cycle is not, so cycle length alone decides it. Note also that the conflict was reported on edge B-C rather than on the chord itself, which is normal, since the algorithm reports wherever the contradiction first surfaces, not the edge you would blame.

Complexity, and where it comes from

Time: O(V + E) · Space: O(V)

This is a single BFS or DFS with one comparison per edge, so it costs exactly one traversal. Every vertex is coloured once and every edge is inspected once from each endpoint. Space is one colour per vertex plus the queue or recursion stack, both O(V). The loop over all vertices adds nothing asymptotically and is what makes disconnected graphs work. There is no faster approach, since deciding bipartiteness requires looking at every edge: a single unexamined edge could be the one creating an odd cycle.

When to use Bipartite Check, and when not to

Bipartiteness is usually a precondition rather than a goal. What you do next depends on why you asked.

AlternativePrefer it whenCost
Hopcroft-KarpThe graph is bipartite and you now want a maximum matching between the two parts.O(E·sqrt(V))
Graph colouringThe graph is not bipartite and you need the actual chromatic number, which is 3 or more.NP-hard in general
Odd cycle detectionYou want the offending cycle itself, not just a yes or no. Reconstruct it from the BFS parent pointers at the conflict edge.O(V + E)
Union-Find with parityEdges arrive incrementally and you want to reject the first one that breaks bipartiteness as it is added.O(E·α(V))

Common pitfalls

  • Only traversing from one vertex. A disconnected graph is bipartite only if every component is. Starting from a single source tests one component and silently passes a graph containing an odd cycle elsewhere. Loop over all vertices and start a fresh traversal from each uncoloured one.
  • Treating uncoloured as a colour. Using 0 for both "unvisited" and "part zero" makes the conflict check misfire. Use a separate sentinel, such as -1 or absence from a map, so that "no colour yet" and "colour 0" are distinguishable.
  • Forgetting that self-loops are fatal. A self-loop is an odd cycle of length 1 and makes a graph non-bipartite immediately. A parent-skipping traversal can miss it entirely, so check for self-loops explicitly.
  • Assuming acyclic implies bipartite is the interesting case. Every tree and every forest is trivially bipartite, since it has no cycles at all. The test only becomes meaningful once cycles exist, so trivial passes on tree-shaped inputs prove very little.
  • Applying it to directed graphs without symmetrising. Bipartiteness is an undirected property. On a directed graph you must decide whether a one-way edge counts as adjacency and treat edges symmetrically, or the answer is not well defined.

Frequently asked questions

What is a bipartite graph?
A bipartite graph is one whose vertices can be split into two sets so that every edge joins a vertex in one set to a vertex in the other, with no edges inside either set. Equivalently, it is a graph that can be properly coloured with two colours, and equivalently again, a graph containing no odd-length cycle.
How do you check if a graph is bipartite?
Run a BFS or DFS, colouring each newly reached vertex the opposite of the vertex you came from. If you ever find an edge whose two endpoints already share a colour, the graph is not bipartite. Repeat from every uncoloured vertex so all components are covered. The whole test is O(V + E).
Why are odd cycles the deciding factor?
Because colours must alternate along any path. Walking round a cycle of even length returns you to the start with the colour you began with, which is consistent. Walking round an odd cycle returns you needing the opposite colour to the one already assigned, which is a contradiction. So a graph is bipartite exactly when it has no odd cycle.
What is the time complexity of checking bipartiteness?
O(V + E) time and O(V) space. It is a single traversal with one colour comparison per edge. This is optimal, because any unexamined edge could be the one that creates an odd cycle, so every edge must be looked at.
What are bipartite graphs used for?
Modelling any two-sided relationship: job applicants and positions, students and courses, buyers and sellers, documents and terms. Once a graph is known to be bipartite, maximum matching becomes efficiently solvable by Hopcroft-Karp, which underlies assignment problems, scheduling and recommendation systems.

Read the full article: Graph Algorithms in Coding Interviews

Related algorithms: Breadth-First Search, Graph Coloring, Maximum Flow

Interactive Controls
Basic Actions
Double Click → Add Node
Drag → Move Nodes
Shift + Click → Connect Nodes
Right Click → Context Menu
Advanced
Ctrl + Click → Multi-Select
Delete Key → Remove Selected
Double Click Edge → Edit Weight
Ctrl + Drag → Pan View

Zoom Controls

100%
Nodes: 4
Edges: 4