DSA interview question
After finding a cycle, the scheduler team wants to know how many tasks are trapped in it, to estimate how much work was repeated. Once Floyd's algorithm finds a meeting point, that point is guaranteed to be inside the cycle. From there, walking forward until you return to the same node counts the cycle's length exactly. If there's no cycle, the length is 0.
Example: 1 -> 2 -> 3 -> 4 -> 5, with 5 linking back to 2 → 4 (the cycle 2, 3, 4, 5).
int loopLength(Node* head); // number of nodes in the cycle, or 0 if there is none
| Input (values, tail links to index) | Output | Explanation |
|---|---|---|
[1, 2, 3, 4, 5], pos 1 | 4 | Nodes 2, 3, 4, 5 |
[25, 14, 19, 33, 10, 21, 39, 90, 58, 45], pos 3 | 7 | From 33 to 45 |
[1], pos 0 | 1 | A self-loop has length 1 |
[1, 2], pos -1 | 0 | No cycle |
[1, 2, 3], pos 0 | 3 | The whole list |
(Confirm: return the number of distinct nodes in the cycle; 0 when the list is acyclic.)
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