700172. Check If Circular Linked List

Easy

Here is the Markdown blog post for the GeeksforGeeks problem "Check If Circular Linked List":

Check If Circular Linked List

Summary

This problem involves checking if a given linked list is circular or not. A circular linked list is one where the last node points back to a previous node, forming a circle instead of ending with a null pointer.

The key concept involved in this problem is understanding how to traverse a linked list and detect whether it forms a cycle or not.

Detailed Explanation

To solve this problem, we can use Floyd's Tortoise and Hare (Cycle Detection) algorithm. This algorithm works by having two pointers, the tortoise and the hare, that move at different speeds through the linked list.

The tortoise moves one step at a time, while the hare moves two steps at a time. If there is no cycle in the linked list, the hare will reach the end of the list. However, if there is a cycle, the hare will eventually meet the tortoise again.

Here's how to implement this algorithm:

  1. Initialize two pointers, tortoise and hare, both pointing to the head of the linked list.
  2. Move the tortoise one step at a time, while moving the hare two steps at a time.
  3. If there is no cycle in the linked list, the hare will reach the end of the list. In this case, return false (not circular).
  4. If the hare meets the tortoise again, it means we've found a cycle. Return true.

Here's an ASCII art diagram to illustrate this algorithm:

       +---+
       | 1 |
       +---+
           |
           v
       +---+  +---+
       | 2 |  | 3 |
       +---+  +---+
           |         |
           v         v
       +---+  +---+  +---+
       | 4 |  | 5 |  | 6 |
       +---+  +---+  +---+
           |         |         |
           v         v         v
       +---+  +---+  +---+  +---+
       | ...|  | ...|  | ...|  | ...|
       +---+  +---+  +---+  +---+

In this diagram, the tortoise and hare start at node 1. The tortoise moves one step at a time (dashed line), while the hare moves two steps at a time (solid line). If there is no cycle, the hare will reach the end of the list. If there is a cycle, the hare will meet the tortoise again.

The time complexity for this algorithm is O(n), where n is the number of nodes in the linked list. The space complexity is O(1) as we only use a few extra variables to store the pointers.

Optimized Solutions

Java

View on GeeksforGeeks
public boolean isCircular(Node head) {
    Node tortoise = head;
    Node hare = head;

    while (hare != null && hare.next != null) {
        tortoise = tortoise.next;
        hare = hare.next.next;

        if (tortoise == hare) {
            return true;
        }
    }

    return false;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.