Check if a linked list is a circular linked list

Pattern: Doubly and circular lists

medium

A circular list comes back to its head. A plain walk might loop forever on a loop that skips the head, so use Floyd's method to find any loop, then walk once round it to see whether the head is on it.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given the head of a singly linked list (with at least one node), return whether it is circular: whether following next from the head eventually comes back to the head. For example, 2 → 4 → 6 → 7 → 5 with 5 pointing back to 2 is circular, and the same list ending in null is not. A list whose last node points back to a later node, such as 1 → 2 → 3 → 4 with 4 pointing to 3, has a loop but is not circular.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name isCircular and the rule about loops that skip the head are this guide's own. The tests build lists from values and the index the last node points back to (-1 for none).

Think first

  • Why might "walk until you see the head again or reach null" never finish?
  • How can you detect any loop safely?
  • Once you know there is a loop, how do you check whether the head is on it?

Hints

    Brute force, and why it fails

    Store visited nodes in a hash set; the list is circular if the first repeated node is the head: O(n) memory. Floyd's method plus one lap uses O(1).

    The key insight

    "Circular" is a loop that includes the head. Separating the two questions, is there a loop and is the head on it, makes the check safe for every shape of list.

    Dry run

    20slow, fast
    41 
    62 
    73 
    54 

    The list is 2 → 4 → 6 → 7 → 5, and 5 points back to 2, the head.

    Step 1 of 4

    The plan

    slow = fast = head
    while fast and fast.next:
        slow = slow.next; fast = fast.next.next
        if slow == fast: stop
    if fast is null or fast.next is null: return false
    cur = slow
    repeat:
        if cur == head: return true
        cur = cur.next
    until cur == slow
    return false
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Floyd's phase and one lap.

    Edge cases

    • One node pointing to itself: circular.
    • One node pointing to null: not circular.
    • A loop that skips the head: not circular.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isCircular(ListNode head) {
            ListNode slow = head, fast = head;      // Floyd's method copes with a loop that skips the head
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                if (slow == fast) break;            // there is some loop
            }
            if (fast == null || fast.next == null) return false;   // the list ends: not circular
            ListNode cur = slow;                    // walk once round the loop: is the head on it?
            do {
                if (cur == head) return true;
                cur = cur.next;
            } while (cur != slow);
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool isCircular(ListNode* head) {
            ListNode *slow = head, *fast = head;    // Floyd's method copes with a loop that skips the head
            while (fast != NULL && fast->next != NULL) {
                slow = slow->next;
                fast = fast->next->next;
                if (slow == fast) break;            // there is some loop
            }
            if (fast == NULL || fast->next == NULL) return false;  // the list ends: not circular
            ListNode* cur = slow;                   // walk once round the loop: is the head on it?
            do {
                if (cur == head) return true;
                cur = cur->next;
            } while (cur != slow);
            return false;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def isCircular(self, head: ListNode) -> bool:
            slow = fast = head                      # Floyd's method copes with a loop that skips the head
            while fast is not None and fast.next is not None:
                slow, fast = slow.next, fast.next.next
                if slow is fast:
                    break                           # there is some loop
            if fast is None or fast.next is None:
                return False                        # the list ends: not circular
            cur = slow                              # walk once round the loop: is the head on it?
            while True:
                if cur is head:
                    return True
                cur = cur.next
                if cur is slow:
                    return False

    Common mistakes

    • Walking until the head returns, which never ends on a loop that skips the head.
    • Calling any loop "circular".
    • Comparing values instead of nodes.

    Similar problems