Is Graph Bipartite solution explained

To check whether a graph is bipartite, try to colour it with two colours so that every edge joins different colours. Start a breadth-first or depth-first search from every node that is not yet coloured, give it one colour, and give each neighbour the opposite colour; if you ever find a neighbour that already has the same colour as the current node, the graph is not bipartite. This visits every node and edge once, so it runs in O(V + E) time with O(V) extra space.

By Published 7 min read

The problem, restated

You are given an undirected graph with nodes numbered 0 to n minus 1, as a list where entry i holds the neighbours of node i. The graph may be split into several disconnected pieces. Decide whether you can divide all the nodes into two groups so that every edge has one end in each group. Return true or false.

Graphs made up for this page
Adjacency listShapeBipartite?
[[1, 3], [0, 2], [1, 3], [2, 0], [5], [4]]a square 0-1-2-3 plus a separate edge 4-5Yes: {0, 2, 4} and {1, 3, 5}
[[1, 2], [0, 2], [0, 1], []]a triangle plus an isolated node 3No: the triangle
[[], [], []]three nodes, no edgesYes
[[1], [0, 2, 3], [1], [1]]a star centred on node 1Yes: {1} and {0, 2, 3}
Graphs made up for this page. Scroll sideways on a small screen.

The triangle fails because any two-colouring of three mutually connected nodes must give two of them the same colour. That generalizes: a graph is bipartite if and only if it has no cycle with an odd number of edges. You do not need to search for odd cycles directly; a failed colouring finds one for you.

Why it comes up

Interviewers use it to see whether you can recognize a graph-colouring question inside a story. The prompt is often disguised: split people into two teams where some pairs dislike each other, schedule exams into two time slots without conflicts, or decide whether a set of "opposite" relationships is consistent. Underneath, each one asks whether a graph is two-colourable. They also check that you handle disconnected graphs, which is where most bugs hide.

  • Possible bipartition. Pairs of people who must be on different teams are given as an edge list. Build the adjacency lists first, then run the same check.
  • Return the two groups. The colour array is the answer; collect the nodes of each colour.
  • Directed edges given. Treat each edge as undirected, or confirm that the input already lists both directions.
  • Very large graphs. An iterative search avoids recursion limits; union-find is another option.

Brute force: try every colouring

Each of the n nodes can take one of two colours, so there are 2^n assignments. For each one, check every edge. If any assignment has no edge with both ends the same colour, the graph is bipartite. This is O(2^n · E) and only usable for tiny graphs, but it is completely independent of the clever solution, which makes it the right reference for random tests.

def bipartite_brute(graph):
    n = len(graph)
    for mask in range(1 << n):
        if all((mask >> u & 1) != (mask >> v & 1)
               for u in range(n) for v in graph[u]):
            return True
    return False
Python: all 2^n colourings. Our test oracle for n up to 9.

Keep a colour for every node, starting as unknown. Loop over all nodes; whenever you meet one that is still unknown, it starts a new component, so colour it 0 and search outward from it. For each node you take from the queue, look at its neighbours. An unknown neighbour gets the opposite colour and joins the queue. A neighbour with the opposite colour is fine. A neighbour with the same colour proves an odd cycle, so return false. If every component finishes without a conflict, return true.

from collections import deque

def is_bipartite(graph):
    color = [-1] * len(graph)
    for start in range(len(graph)):
        if color[start] != -1:
            continue
        color[start] = 0
        queue = deque([start])
        while queue:
            node = queue.popleft()
            for nb in graph[node]:
                if color[nb] == -1:
                    color[nb] = 1 - color[node]
                    queue.append(nb)
                elif color[nb] == color[node]:
                    return False
    return True
Python: BFS two-colouring from every uncoloured node. O(V + E).
function isBipartite(graph) {
  const color = new Array(graph.length).fill(-1);
  for (let start = 0; start < graph.length; start++) {
    if (color[start] !== -1) continue;
    color[start] = 0;
    const stack = [start];
    while (stack.length > 0) {
      const node = stack.pop();
      for (const nb of graph[node]) {
        if (color[nb] === -1) {
          color[nb] = 1 - color[node];
          stack.push(nb);
        } else if (color[nb] === color[node]) {
          return false;
        }
      }
    }
  }
  return true;
}
JavaScript: the same colouring with an explicit DFS stack.

Whether you pick BFS or DFS does not matter for correctness; both colour each component consistently. A self-loop (a node listed as its own neighbour) is caught automatically, because the node and its "neighbour" have the same colour.

Another route: union-find

All neighbours of a node must share one colour, the one opposite to the node. So for each node, union all of its neighbours into one set, and check along the way that the node itself is never in the same set as any neighbour. It is close to linear in practice and is handy when edges arrive one at a time, though the search version is simpler to explain in an interview.

def is_bipartite_dsu(graph):
    parent = list(range(len(graph)))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for node, nbs in enumerate(graph):
        for nb in nbs:
            if find(node) == find(nb):
                return False
            parent[find(nb)] = find(nbs[0])
    return True
Python: union-find with path halving. Near-linear in practice; add union by size for the α(V) bound.

Complexity

V nodes, E edges
ApproachTimeExtra space
Every colouringO(2^V · E)O(V)
BFS two-colouringO(V + E)O(V) for colours and the queue
DFS two-colouring (stack)O(V + E)O(V)
Union-find, path halving onlyO((V + E) log V) at worst, near-linear in practiceO(V)
V nodes, E edges. Scroll sideways on a small screen.

Edge cases

  • A disconnected graph: start a search from every uncoloured node, or a component after the first is never checked.
  • Isolated nodes and a graph with no edges: bipartite.
  • A graph with zero nodes: bipartite (nothing can conflict).
  • A self-loop: never bipartite.
  • An even cycle (bipartite) next to an odd cycle (not) in a separate component: the answer is false.
  • Recursive DFS on a long path can exceed Python's default recursion limit, which is why the versions above are iterative.

Mistakes to avoid

  • Starting the search only from node 0, which ignores every other component.
  • Using a visited flag without colours, which cannot tell a safe revisit from a conflict.
  • Recolouring an already coloured node instead of comparing, which hides the conflict.
  • Assuming the adjacency list is symmetric when the problem gives a one-way edge list.
  • In union-find, forgetting the check between a node and its own neighbours before uniting them.

How to explain it out loud

Fictional example

Naming the colouring idea first
Candidate
Splitting nodes into two groups with every edge crossing is the same as colouring the graph with two colours so neighbours differ.
Candidate
I will colour as I search: the start node gets 0, its neighbours get 1, and so on. If a neighbour already has my colour, there is an odd cycle and I return false.
Candidate
The graph might be disconnected, so I loop over every node and start a new search wherever the colour is still unset. Each node and edge is handled once, so O(V plus E).
Interviewer
What if I wanted the two groups?
Candidate
The colour array already holds them. I would just collect the zeros and the ones.

Alien Dictionary is the other graph problem in this set, where you build the graph from words before searching it. All Nodes Distance K in a Binary Tree uses the same level-by-level BFS. Number of Islands has the same "start a search from every unvisited node" outer loop on a grid.

Where Natively fits

Story-style graph problems are good practice for spotting the model hiding in the prompt. In a practice round on Mac or Windows, Natively can read the scenario from a screenshot, and if you cannot see the graph in it, you can ask it for that single hint before writing the colouring yourself. Reviewing the transcript afterward shows whether you raised disconnected graphs on your own. Learn more about the AI interview assistant.

Questions people ask

How do you check if a graph is bipartite?

Colour it with two colours during a BFS or DFS, giving each neighbour the opposite colour. If a neighbour already has the same colour as the current node, the graph is not bipartite.

Why must the search start from every node?

The graph can be disconnected. Starting a new search from each uncoloured node makes sure every component is checked.

What is the time complexity of Is Graph Bipartite?

O(V + E) time and O(V) extra space, since each node and edge is processed once.

What makes a graph not bipartite?

A cycle with an odd number of edges, such as a triangle. A self-loop also rules it out.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP