Day 12 - Linked List Cycle

🧩 Problem:

Given a singly linked list, determine if it contains a cycle.

A cycle means a node’s next pointer eventually points back to a previous node.

🧪 Example:

Input:
head = [3,2,0,-4], pos = 1 (cycle back to node with value 2)
Output: True

Input:
head = [1,2], pos = -1 (no cycle)
Output: False

🧠 How to Approach It

❌ Brute force would use a set() to track visited nodes — O(n) space.

✅ Instead, we use Floyd’s Cycle Detection Algorithm (Tortoise & Hare):

  • 🐢 slow pointer moves 1 step

  • 🐇 fast pointer moves 2 steps

  • If they meet: cycle exists

  • If fast or fast.next is None: no cycle

This technique detects loops without modifying the list or using extra memory.

✅ Python Solution:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[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

⏱ Time & Space Complexity:

  • Time: O(n) — each pointer visits each node at most once

  • Space: O(1) — constant space, no extra data structures

💬 TL;DR:

  • Don’t track nodes in a set.

  • Use two pointers.

  • If they meet, you found a cycle. If not, no cycle.

This trick shows up again and again in linked list problems.
It’s an interview favorite — master it once, use it forever