DSA interview question
A utility company models its power lines as an undirected graph and needs to know whether the network contains any loop, because a loop means redundant paths that affect protection settings. Run BFS from every unvisited vertex, remembering which vertex discovered each vertex (its BFS parent). If an edge leads to an already visited vertex that isn't the parent, a second path to that vertex exists, so there's a cycle.
Example: 5 vertices, edges 0-1, 1-2, 2-3, 3-4, 4-1 → true (cycle 1-2-3-4).
bool isCycleBFS(int V, const vector<vector<int>>& adj); // simple undirected graph
Input (V, edges) | Output | Explanation |
|---|---|---|
(5, [[0,1],[1,2],[2,3],[3,4],[4,1]]) | true | 1-2-3-4-1 |
(3, [[0,1],[1,2],[2,0]]) | true | A triangle |
(4, [[1,2],[2,3]]) | false | A path, and vertex 0 is isolated |
(4, [[0,1],[2,3]]) | false | A forest of two edges |
(1, []) | false |
(Confirm: the graph is simple (no self-loops, no parallel edges) and may be disconnected.)
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