PXProLearnX
Sign in (soon)
Data Structures and Algorithmshardconcept

How would you detect a cycle in a linked list?

Explanation:

Detecting a cycle in a linked list is a common problem that can be efficiently solved using Floyd's Tortoise and Hare algorithm. This algorithm uses two pointers that traverse the linked list at different speeds. If there is a cycle, the fast pointer (hare) will eventually meet the slow pointer (tortoise), indicating a cycle exists.

Key Talking Points:

  • Purpose: Detect if a linked list contains a cycle.
  • Approach: Use Floyd's Tortoise and Hare algorithm.
  • Time Complexity: O(n) - where n is the number of nodes in the linked list.
  • Space Complexity: O(1) - no extra space required.

NOTES:

Reference Table:

ApproachTime ComplexitySpace ComplexityNotes
Floyd's Tortoise and HareO(n)O(1)Efficient, uses two pointers
Hash TableO(n)O(n)Uses extra space to store visited nodes

Pseudocode:

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

   def has_cycle(head):
       slow = head
       fast = head

       while fast and fast.next:
           slow = slow.next
           fast = fast.next.next

           if slow == fast:
               return True

       return False

Follow-Up Questions and Answers:

  1. How would you find the start of the cycle in a linked list?

    • Answer: Once a cycle is detected using Floyd's Tortoise and Hare algorithm, reset one pointer to the head of the list and keep the other at the meeting point. Move both pointers one step at a time. The point where they meet is the start of the cycle.
  2. Can you modify the linked list to remove the cycle?

    • Answer: Yes, once the start of the cycle is found, traverse the cycle to find the node just before the start node of the cycle and set its next pointer to None to break the cycle.
  3. What are the limitations of this approach?

    • Answer: Floyd's Tortoise and Hare algorithm assumes that the linked list is singly linked and that the node structure allows for two pointers to be moved independently. It may not be applicable if the list is manipulated concurrently by other threads or processes.
Want all 100 questions?
Get the full book on Amazon — paperback, Kindle, or hardcover.