PPractick

DSA interview question

Detect a Loop in a Linked List

Medium · Data structures · Topics: linkedlist, two pointer

The problem

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.

Function signature

bool hasCycle(Node* head);

Test cases

Input (values, tail links to index)OutputExplanation
[3, 2, 0, -4], pos 1true-4 links back to 2
[1, 2], pos 0true2 links back to 1
[1], pos 0trueA self-loop
[1], pos -1falseNo cycle
[1, 2, 3], pos -1false
[]falseEmpty 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Can I modify the list (for example, mark visited nodes)?
  2. Is O(1) extra space required?
  3. Return a boolean or the meeting node?

Follow-ups to expect

  1. "Why must the pointers meet if there's a cycle?"
  2. "Why step 2 and not 3?"
  3. "What's the hash-set approach?"
  4. "How long does Floyd's take?"
  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