DSA interview question
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.
bool isBipartite(const vector<vector<int>>& graph); // undirected adjacency list
| Input (adjacency list) | Output | Explanation |
|---|---|---|
[[1,3],[0,2],[1,3],[0,2]] | true | Teams {0, 2} and {1, 3} |
[[1,2,3],[0,2],[0,1,3],[0,2]] | false | Triangle 0-1-2 |
[[1,2],[0,2],[0,1]] | false | A triangle is an odd cycle |
[[],[2],[1]] | true | Disconnected; 0 is isolated |
[[1],[0],[3],[2]] | true | Two separate edges |
(Confirm: the graph is undirected and may be disconnected; no self-loops.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in