How do you detect a loop in a linked list and find its start node?

DSA
Medium
Goldman Sachs
105.3K views

This question asks candidates to implement an algorithm that identifies cycles within a singly linked list and pinpoints the exact node where the cycle begins.

Why Interviewers Ask This

Interviewers use this problem to assess a candidate's mastery of pointer manipulation and fundamental graph traversal algorithms. Specifically, they look for knowledge of Floyd’s Cycle Detection Algorithm, often called the Tortoise and Hare approach. The ability to solve this efficiently demonstrates strong logical reasoning and understanding of time-space trade-offs, as the optimal solution requires O(n) time and O(1) space.

How to Answer This Question

Start by clearly explaining the two-pointer technique: one slow pointer moving one step at a time and a fast pointer moving two steps. Explain how their meeting point confirms a cycle exists. Then, detail the second phase where you reset one pointer to the head and move both at the same speed until they meet again; this new meeting point is the start of the loop. Always mention edge cases like empty lists or single-node loops before writing code.

Key Points to Cover

  • Use Floyd's Tortoise and Hare algorithm
  • Detect cycle existence via pointer collision
  • Find start node by resetting one pointer
  • Achieve O(n) time and O(1) space

Sample Answer

To detect a loop, I would use Floyd’s Cycle Detection Algorithm with two pointers, slow and fast. The slow pointer moves one step while the fast pointer moves two steps. If they meet, a cycle exists. To find the start node, I reset the slow pointer to the head and move both pointers one step at a time. They will meet exactly at the starting node of the loop. This approach ensures O(n) time complexity and O(1) space complexity, which is optimal for this problem.

Common Mistakes to Avoid

  • Failing to handle null pointer exceptions
  • Using extra space like a hash set unnecessarily
  • Not explaining the mathematical proof for finding the start node

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 35 DSA questionsBrowse all 13 Goldman Sachs questions