Data Structures & Algorithms Linked Lists
💡
Exercise 64

Linked List Cycle 20 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a linked list, determine if it has a cycle — meaning some node's next pointer points back to a previous node, creating an infinite loop.

Use Floyd's Tortoise and Hare algorithm: two pointers moving at different speeds. If there's a cycle, the fast pointer will eventually meet the slow pointer.

💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀

Time: O(n), Space: O(1). This is much better than using a hash set (O(n) space).

📋 Instructions
Implement `has_cycle(head)` using Floyd's algorithm. Test with a list that has a cycle and one that doesn't. Print both results.
Slow pointer moves 1 step, fast moves 2. If fast catches slow, there's a cycle. If fast reaches None, no cycle.
⚠️ Try solving it yourself first — you'll learn more!
# slow moves 1 step, fast moves 2 steps
# If no cycle: fast reaches None
# If cycle: they meet inside the cycle!
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False
🧪 Test Cases
Input
has_cycle(head1)
Expected
False
Boolean check
Input
has_cycle(head2)
Expected
True
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.