LinkedListProblem 16 of 36

Check if a linked list is a circular linked list

Brute Force
Time: O(n)
Space: O(n)
Optimal
Time: O(n)
Space: O(1)

Check if a Linked List is Circular

Problem Statement

A circular linked list is a linked list where the last node points back to the head (first node), forming a complete circle. Given a linked list, determine if it is circular.

Note: This is different from detecting a cycle - a circular list specifically has the last node pointing to the head.

Example

Input: 1 -> 2 -> 3 -> 4 -> 5 -> (back to 1) Output: true (circular) Input: 1 -> 2 -> 3 -> 4 -> 5 -> null Output: false (not circular, ends with null) Input: 1 -> 2 -> 3 -> 4 -> 5 -> 3 (back to 3) Output: false (has cycle but not circular - doesn't point to head)

Brute Force Approach (Using HashSet)

Intuition

Traverse the list and store visited nodes. If we encounter the head again before reaching null, it's circular.

Algorithm

  1. If list is empty, return false
  2. Store head in a set
  3. Traverse the list
  4. If we reach null, return false
  5. If we reach head again, return true
  6. If we reach any other visited node, return false (cycle but not circular)

Implementation

Complexity Analysis

  • Time Complexity: O(n) - Visit each node once
  • Space Complexity: O(n) - HashSet stores all nodes

Optimal Approach (Simple Traversal)

Intuition

A simpler approach: Just traverse the list and check if any node's next pointer points to head. If we reach null first, it's not circular.

Algorithm

  1. If list is empty, return false
  2. Start from head and traverse
  3. If any node's next is head, return true
  4. If we reach null, return false

Implementation

Complexity Analysis

  • Time Complexity: O(n) - Visit each node once
  • Space Complexity: O(1) - Only using one pointer

Alternative: Using Floyd's Cycle Detection

Intuition

We can use Floyd's algorithm to detect if there's a cycle, and then check if the cycle includes the head.

Implementation


Circular vs Has Cycle

| Property | Circular | Has Cycle | |----------|----------|-----------| | Definition | Last node → Head | Any node → Previous node | | Example | 1→2→3→1 | 1→2→3→2 | | Cycle Start | Always at Head | Can be anywhere | | Detection | Check if any next == head | Floyd's algorithm |


Creating a Circular Linked List


Key Takeaways

  1. A circular list has its last node pointing to the head
  2. The simple traversal approach is O(1) space and very clean
  3. Different from cycle detection - circular means cycle starts at head
  4. Floyd's algorithm can be adapted but is overkill for this problem
  5. When creating circular lists, ensure the last node always points to head
  6. Single node circular list: head.next = head
  7. This concept is used in round-robin scheduling and buffer implementations