DSA interview question
A bug in a job scheduler occasionally makes the last task in a linked list point back to an earlier task, creating a cycle. Any code that walks the list then spins forever. The monitor needs to detect this. A hash set of visited nodes works but uses O(n) memory. Floyd's cycle detection (tortoise and hare) uses O(1): move a slow pointer one step and a fast pointer two steps. If there's no cycle, fast reaches the end; if there is one, fast eventually laps slow and they meet.
Example: 3 -> 2 -> 0 -> -4, with -4 linking back to 2 → true.
bool hasCycle(Node* head);
| Input (values, tail links to index) | Output | Explanation |
|---|---|---|
[3, 2, 0, -4], pos 1 | true | -4 links back to 2 |
[1, 2], pos 0 | true | 2 links back to 1 |
[1], pos 0 | true | A self-loop |
[1], pos -1 | false | No cycle |
[1, 2, 3], pos -1 | false | |
[] | false | Empty list |
(Confirm: pos is the index the tail links back to, or -1 for no cycle; pos is used only to build the test, the function receives just the head.)
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