PPractick

DSA interview question

Is the Graph Bipartite? (DFS Colouring)

Hard · Data structures · Topics: graph, dfs, bipartite

The problem

A school wants to split students into two teams so that every pair of rivals (an edge) ends up on different teams. That's possible exactly when the rivalry graph is bipartite. Try to 2-colour it with DFS: give the start vertex colour 0, give every neighbour the opposite colour, and continue. If you ever find an edge whose two endpoints have the same colour, it's impossible, which happens exactly when the graph has an odd cycle. Components are coloured independently.

Example: [[1,3], [0,2], [1,3], [0,2]] (a 4-cycle) → true; [[1,2,3], [0,2], [0,1,3], [0,2]] → false.

Function signature

bool isBipartite(const vector<vector<int>>& graph);  // undirected adjacency list

Test cases

Input (adjacency list)OutputExplanation
[[1,3],[0,2],[1,3],[0,2]]trueTeams {0, 2} and {1, 3}
[[1,2,3],[0,2],[0,1,3],[0,2]]falseTriangle 0-1-2
[[1,2],[0,2],[0,1]]falseA triangle is an odd cycle
[[],[2],[1]]trueDisconnected; 0 is isolated
[[1],[0],[3],[2]]trueTwo separate edges

(Confirm: the graph is undirected and may be disconnected; no self-loops.)

How interviewers phrase it

Clarifying questions to ask

  1. Can the graph be disconnected? (Yes, so colour every component.)
  2. Self-loops? (None. A self-loop would make it non-bipartite.)
  3. Size? (Up to 100 vertices here; the method is linear anyway.)

Follow-ups to expect

  1. "Why does a conflict prove it's impossible?"
  2. "Why is the colouring forced?"
  3. "BFS version?"
  4. "Union-find version?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in