Linked List Cycle Detection (Floyd's Algorithm)

viaGlassdoor

Problem: Given the head of a linked list, determine whether the linked list has a cycle in it, and optionally find the node where the cycle begins.

Constraints: List may contain up to 10^4 nodes.

Example: A list where the tail connects back to an earlier node forms a cycle; a null-terminated list has no cycle.

Approach: Use Floyd's Cycle Detection (tortoise and hare): a slow pointer advances one node at a time, a fast pointer advances two nodes at a time; if they meet, a cycle exists. To find the cycle's start node, reset one pointer to the head and advance both pointers one step at a time until they meet again — that meeting point is the cycle's entry node. O(n) time, O(1) space.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account