PPractick

DSA interview question

Length of the Loop in a Linked List

Medium · Data structures · Topics: linkedlist, two pointer

The problem

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).

Function signature

int loopLength(Node* head);  // number of nodes in the cycle, or 0 if there is none

Test cases

Input (values, tail links to index)OutputExplanation
[1, 2, 3, 4, 5], pos 14Nodes 2, 3, 4, 5
[25, 14, 19, 33, 10, 21, 39, 90, 58, 45], pos 37From 33 to 45
[1], pos 01A self-loop has length 1
[1, 2], pos -10No cycle
[1, 2, 3], pos 03The whole list

(Confirm: return the number of distinct nodes in the cycle; 0 when the list is acyclic.)

How interviewers phrase it

Clarifying questions to ask

  1. What should be returned when there's no loop? (0.)
  2. May I modify the list?
  3. Is O(1) extra space required?

Follow-ups to expect

  1. "Why is the meeting point inside the cycle?"
  2. "How do you count the length?"
  3. "Can you get the length from the cycle's entrance instead?"
  4. "How does the length help remove the cycle?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in