AlgoTales · Roadmap

Bipartite graphs

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A bipartite graph is a network that can be split into two sides so that every link joins one side to the other, never within a side. Checking this is just two-colouring, and it tells you if a clean two-group split exists.

Practical use cases

  • Web app: Matching candidates to jobs. A job portal has candidates on one side and openings on the other, and links mean "applied". Because links only go across, it is a bipartite graph, which opens the door to matching tools that assign each person to at most one job.
  • Web app: Splitting players into two teams. A fantasy or quiz app has a list of "these two must not be on the same team" pairs. Colouring players red and blue by going through the pairs tells you whether a valid split exists, or points at the pair that makes it impossible.
  • Web app: Customers and products recommendations. A shop links customers to the products they bought. Because the data is split in two kinds, the app can also compute similarity between customers by looking at the products they share.
  • System: Odd-cycle check. A graph is two-sided exactly when it has no cycle with an odd number of steps. Schedulers use this to know if tasks can be placed on two machines without conflict.

The story: Two Teams for the Kabaddi Match

Before the kabaddi match, Mrs. Sharma had a rule: kids who quarrel must not be on the same team. Mira had a list of quarrels. "Can we make two teams so every quarrel crosses between teams?" she wondered. Trying all the combinations would take forever.

Mira found a calmer way. She put Aarav on Team 1. Everyone who quarrelled with Aarav had to go on Team 2. Whoever quarrelled with those kids had to go on Team 1 again. She spread the colours outward, ring by ring, just like BFS.

Most days it worked. Then one day three kids all quarrelled with each other: Zoya, Kabir and Aarav. Put Zoya on Team 1, then Kabir and Aarav must both be on Team 2, but they quarrel with each other! Impossible.

A graph that can be split into two groups with every edge going between the groups is bipartite. It works exactly when the graph has no cycle of odd length (like a triangle).

How to spot this problem, and where you need it

You have items with "conflict" or "relationship" links and want to know whether they can be sorted into exactly two groups, or whether the data naturally has two kinds of things.

Signs you need it

  • The statement says "divide into two groups so that no pair of enemies, conflicts or rivals are together".
  • Your data has two different kinds of records and links only ever go between kinds, such as users and products or students and courses.
  • You want to match one set of things with another, such as drivers with riders or interns with projects.

Where to use it in a project

  • Validating a "cannot sit together" or "cannot be in the same team" list before generating a seating or team plan.
  • Building a match feature that pairs people with jobs, drivers with trips or tutors with students.

The solution

Give the first node colour red. Do a BFS or DFS: every neighbour of a red node gets blue, and every neighbour of a blue node gets red. If you ever find a neighbour that already has the same colour as the current node, the split is impossible. Repeat from every unvisited node, since the network may have several separate parts. If you finish without a clash, the two colours are your two groups.

Payoff: Before: trying team splits by hand for 40 players. After: one pass over the pairs gives a valid split or names the conflicting pair.

Explain it like I am 8

Colour the dots with two crayons, red and blue. The only rule: two dots joined by a line must have different colours. If you can colour the whole picture without breaking the rule, the picture is bipartite.

How it works, step by step

  1. Colour the start vertex with colour 1 and put it in a queue.
  2. Take a vertex from the queue. Every neighbour with no colour gets the opposite colour and joins the queue.
  3. If a neighbour already has the same colour as the current vertex, stop: the graph is not bipartite.
  4. Repeat until the queue is empty. Restart from any uncoloured vertex in case the graph has several components.
  5. If you never hit a conflict, the colours are your two teams.

The code in four languages

PHP

<?php
// BFS 2-colouring. Returns true when the graph is bipartite.
function isBipartite(array $graph): bool {
    $color = [];
    foreach (array_keys($graph) as $start) {
        if (isset($color[$start])) continue;      // other components too
        $color[$start] = 1;
        $queue = new SplQueue();
        $queue->enqueue($start);
        while (!$queue->isEmpty()) {
            $u = $queue->dequeue();
            foreach ($graph[$u] as $v) {
                if (!isset($color[$v])) {
                    $color[$v] = 3 - $color[$u];  // opposite team (1 <-> 2)
                    $queue->enqueue($v);
                } elseif ($color[$v] === $color[$u]) {
                    return false;                 // same team but connected
                }
            }
        }
    }
    return true;
}

$square = ['A'=>['B','D'], 'B'=>['A','C'], 'C'=>['B','D','E'], 'D'=>['C','A'], 'E'=>['C']];
$triangle = ['X'=>['Y','Z'], 'Y'=>['X','Z'], 'Z'=>['Y','X']];
echo 'Square + tail bipartite? ' . (isBipartite($square) ? 'yes' : 'no') . "\n";
echo 'Triangle bipartite? ' . (isBipartite($triangle) ? 'yes' : 'no') . "\n";

JavaScript

// BFS 2-colouring. Returns true when the graph is bipartite.
function isBipartite(graph) {
  const color = {};
  for (const start of Object.keys(graph)) {
    if (color[start] !== undefined) continue;     // other components too
    color[start] = 1;
    const queue = [start];
    let head = 0;
    while (head < queue.length) {
      const u = queue[head++];
      for (const v of graph[u]) {
        if (color[v] === undefined) {
          color[v] = 3 - color[u];                // opposite team (1 <-> 2)
          queue.push(v);
        } else if (color[v] === color[u]) {
          return false;                           // same team but connected
        }
      }
    }
  }
  return true;
}

const square = { A: ['B','D'], B: ['A','C'], C: ['B','D','E'], D: ['C','A'], E: ['C'] };
const triangle = { X: ['Y','Z'], Y: ['X','Z'], Z: ['Y','X'] };
console.log('Square + tail bipartite? ' + (isBipartite(square) ? 'yes' : 'no'));
console.log('Triangle bipartite? ' + (isBipartite(triangle) ? 'yes' : 'no'));

Java

import java.util.*;

public class Main {
    // BFS 2-colouring. Returns true when the graph is bipartite.
    static boolean isBipartite(Map<String, List<String>> graph) {
        Map<String, Integer> color = new HashMap<>();
        for (String start : graph.keySet()) {
            if (color.containsKey(start)) continue;       // other components too
            color.put(start, 1);
            Queue<String> queue = new ArrayDeque<>();
            queue.add(start);
            while (!queue.isEmpty()) {
                String u = queue.remove();
                for (String v : graph.get(u)) {
                    if (!color.containsKey(v)) {
                        color.put(v, 3 - color.get(u));   // opposite team (1 <-> 2)
                        queue.add(v);
                    } else if (color.get(v).equals(color.get(u))) {
                        return false;                     // same team but connected
                    }
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        var square = Map.of("A", List.of("B", "D"), "B", List.of("A", "C"),
                            "C", List.of("B", "D", "E"), "D", List.of("C", "A"), "E", List.of("C"));
        var triangle = Map.of("X", List.of("Y", "Z"), "Y", List.of("X", "Z"), "Z", List.of("Y", "X"));
        System.out.println("Square + tail bipartite? " + (isBipartite(square) ? "yes" : "no"));
        System.out.println("Triangle bipartite? " + (isBipartite(triangle) ? "yes" : "no"));
    }
}

Go

package main

import "fmt"

// isBipartite does BFS 2-colouring. It returns true when the graph is bipartite.
func isBipartite(graph map[string][]string) bool {
	color := map[string]int{} // 0 = not coloured yet
	for start := range graph {
		if color[start] != 0 {
			continue // other components too
		}
		color[start] = 1
		queue := []string{start}
		for head := 0; head < len(queue); head++ {
			u := queue[head]
			for _, v := range graph[u] {
				if color[v] == 0 {
					color[v] = 3 - color[u] // opposite team (1 <-> 2)
					queue = append(queue, v)
				} else if color[v] == color[u] {
					return false // same team but connected
				}
			}
		}
	}
	return true
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	square := map[string][]string{"A": {"B", "D"}, "B": {"A", "C"}, "C": {"B", "D", "E"}, "D": {"C", "A"}, "E": {"C"}}
	triangle := map[string][]string{"X": {"Y", "Z"}, "Y": {"X", "Z"}, "Z": {"Y", "X"}}
	fmt.Println("Square + tail bipartite? " + yesNo(isBipartite(square)))
	fmt.Println("Triangle bipartite? " + yesNo(isBipartite(triangle)))
}

Time: O(V + E) · Extra space: O(V). It is just a BFS with an extra colour value attached to each vertex.

Watch out for

  • Colouring only the component of the first vertex. Loop over all vertices to cover disconnected graphs.
  • Treating "colour exists" as enough. You must compare the colour with the current vertex's colour.
  • Believing a graph with an even cycle is not bipartite. Only odd cycles (3, 5, 7…) break it.

Quick check

  1. Which graph can never be bipartite?
    • A square (4-cycle)
    • A straight line
    • A triangle (3-cycle)
  2. During BFS you meet a connected neighbour with the SAME colour as you. What do you do?
    • Declare the graph not bipartite
    • Recolour it
    • Skip it
  3. Why loop over every start vertex?
    • To find shorter paths
    • The graph may have several separate pieces
    • To sort the colours