Skip to the solution
MediumDSA14 min read

How do you check if a graph is bipartite?

987 views

The problem

Question presented to candidate: "You are given an undirected graph as an adjacency list — graph[u] is the list of nodes joined to u. Return whether the graph is bipartite: can you split the nodes into two groups so that every edge goes between the groups? The graph may be disconnected. Please write it in Python."

What a strong answer should cover:

  • The reformulation: bipartite ⇔ the graph can be 2-coloured ⇔ it has no odd cycle.
  • BFS (or DFS) colouring: give each uncoloured neighbour the opposite colour; a neighbour with the same colour means False.
  • An outer loop over every node so each connected component gets its own traversal.
  • O(V + E) time and O(V) extra space, plus the free result: the colour array is the two sides.
  • Python specifics: collections.deque with popleft() for the queue, building adjacency lists with a list comprehension (never [[]] * n), and recursion depth limits if you write the DFS recursively.

Clarifying questions expected:

  • Can the graph be disconnected or contain self-loops?
  • Do you need only the yes/no answer, or the two groups too?

Code / implementation expected: Yes — an is_bipartite(graph) function in Python with a colour list and BFS, tested on a bipartite graph, a triangle and a disconnected graph.

  • graphs
  • bfs
  • coloring

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read · 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBFS 2-colouring on eight graphs, printing both sides when it succeeds
PythonBFS vs iterative DFS vs union-find agree on 500 random graphs

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 51 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you generate all subsets of an array?

Continue