DSA interview question
A university schedules exams into m time slots. Two exams that share a student must not be in the same slot. Modelled as a graph (exams are vertices, conflicts are edges), the question is: can the vertices be coloured with at most m colours so that no edge connects two vertices of the same colour? This is NP-complete in general, so the interview solution is backtracking: colour vertices one at a time, try each colour that no already-coloured neighbour uses, and undo when a vertex has no legal colour.
Example: 4 vertices with edges 0–1, 1–2, 2–3, 3–0, 0–2, m = 3 → true.
bool graphColoring(int V, const vector<pair<int, int>>& edges, int m);
Input (V, edges, m) | Output | Explanation |
|---|---|---|
(4, [0-1, 1-2, 2-3, 3-0, 0-2], 3) | true | For example colours 1, 2, 3, 2 |
(4, [0-1, 1-2, 2-3, 3-0, 0-2], 2) | false | Vertices 0, 1, 2 form a triangle |
(5, [0-1, 1-2, 2-3, 3-4, 4-0], 2) | false | An odd cycle needs 3 colours |
(3, [0-1, 1-2], 2) | true | A path alternates colours |
(1, [], 1) | true |
(Confirm: the graph is undirected with no self-loops; colours are 1..m; only adjacent vertices must differ.)
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