Medium Data Structures Linked Lists
How do you detect a cycle in a linked list?
Answer
The optimal approach is Floyd's Cycle Detection (tortoise and hare) algorithm using two pointers: slow moves one step at a time, fast moves two steps. If there's a cycle, they will eventually meet; if fast reaches null, there's no cycle. Time complexity is O(n), space is O(1). To find the cycle start, after detection, move one pointer to head and advance both by one until they meet again.
IIT Certified
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.
Relevant for Roles
Software Engineer Backend Developer Algorithm Developer