Coding Easy Software Engineer Backend Full Stack

Determine if a linked list contains a cycle (Floyd's Tortoise and Hare Cycle Detection).

Practise this question with AI feedback

Record your spoken answer or type your response to receive immediate scoring and STAR improvements.

💡 Suggested Approach & Sample Answer

Optimal Two-Pointer Approach (Floyd's Cycle-Finding Algorithm):
- Use a slow pointer moving 1 step and a fast pointer moving 2 steps; if a cycle exists, they must collide.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def has_cycle(head: ListNode) -> bool:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False

Complexity & Key Logic:
- Time Complexity: O(N). In the worst case, fast travels at most 2 times the cycle length to catch slow.
- Space Complexity: O(1) constant auxiliary space.
- Algorithm Details:
- If the list has no cycle, fast or fast.next reaches None, returning False.
- If a cycle exists, fast enters the loop first. With each step, the distance between fast and slow decreases by 1 node until they meet.

🎯 What Interviewers Listen For

How would you answer this in a real interview?

Use our free AI mock practice tool to test your response, analyze speaking pacing, and refine your STAR structure.

🔗 Related Coding Questions