Length of loop in LL

Pattern: Fast and slow pointers

medium

Find a meeting point inside the loop with slow and fast pointers, then walk once around the loop from there, counting nodes until you are back.

The problem

Given the head of a linked list, return the number of nodes in its loop, or 0 if it has no loop. For example, 3 → 2 → 0 → -4 with the last node pointing back to 2 gives 3.

The function name findLengthOfLoop matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • How do you know there is a loop at all?
  • Once you stand on any node inside the loop, how do you measure it?
  • Is the meeting point of slow and fast always inside the loop?

Hints

    Brute force, and why it fails

    Store each node with its step number in a hash map; at the first repeat, the loop length is the difference of steps. O(n) memory. Floyd's method plus one lap needs O(1).

    The key insight

    Any node inside a loop is a starting line. One lap from it measures the loop, and Floyd's meeting point is a node you already have inside the loop.

    Dry run

    30 
    21 
    02 
    -43slow

    The list is 3 → 2 → 0 → -4, and -4 points back to 2. slow and fast meet on -4, which is inside the loop.

    Step 1 of 4

    The plan

    slow = fast = head
    while fast and fast.next:
        slow = slow.next; fast = fast.next.next
        if slow == fast:
            length = 1, cur = slow.next
            while cur != slow: length = length + 1; cur = cur.next
            return length
    return 0
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Floyd's phase is O(n), and the lap is at most n steps.

    Edge cases

    • No loop: 0.
    • A node pointing to itself: 1.
    • The whole list is the loop: n.
    I've built my logic, show the code

    Java

    class Solution {
        public int findLengthOfLoop(ListNode head) {
            ListNode slow = head, fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                if (slow == fast) {                 // inside the loop: walk once around it
                    int length = 1;
                    for (ListNode cur = slow.next; cur != slow; cur = cur.next) length++;
                    return length;
                }
            }
            return 0;                               // no loop
        }
    }

    C++

    class Solution {
    public:
        int findLengthOfLoop(ListNode* head) {
            ListNode *slow = head, *fast = head;
            while (fast != NULL && fast->next != NULL) {
                slow = slow->next;
                fast = fast->next->next;
                if (slow == fast) {                 // inside the loop: walk once around it
                    int length = 1;
                    for (ListNode* cur = slow->next; cur != slow; cur = cur->next) length++;
                    return length;
                }
            }
            return 0;                               // no loop
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def findLengthOfLoop(self, head: ListNode) -> int:
            slow = fast = head
            while fast is not None and fast.next is not None:
                slow, fast = slow.next, fast.next.next
                if slow is fast:                    # inside the loop: walk once around it
                    length, cur = 1, slow.next
                    while cur is not slow:
                        length, cur = length + 1, cur.next
                    return length
            return 0                                # no loop

    Common mistakes

    • Counting from the head instead of from inside the loop.
    • Starting the count at 0 and stopping on the start node, which is off by one.
    • Comparing values instead of nodes.

    Similar problems