Easy
Linked List Cycle
👶 The 5-Year-Old Summary
You're in a treasure hunt room. Some treasure hunts end at "null" (no more clues), but some loops back to a previous room! Detect if you're stuck in a loop!
🎮 Interactive Visualizer
Floyd's Tortoise & Hare Algorithm!
List: 3 → 2 → 0 → -4 → (back to 2)
🐢 Slow (1 step)
-
🐇 Fast (2 steps)
-
🧠 The Brain Hack
Floyd's Cycle Detection! Use two pointers - slow moves 1 step, fast moves 2 steps. If there's a cycle, they MUST meet! It's like two runners on a circular track!
💻 The Clean Solution
def has_cycle(head):
if not head or not head.next:
return False
# Start at head
slow = head
fast = head
# Move slow by 1, fast by 2
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# They met = cycle exists!
if slow == fast:
return True
# Fast reached end = no cycle
return False
Time: O(n)
Space: O(1)