Linked List Cycle - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

⚠️ Important Notes

  • đź’ˇ Space-optimized alternative:
    This approach uses extra memory for the visited set. A memory-constant alternative is Floyd’s Cycle Detection (the tortoise and hare algorithm), which also detects cycles in O(n) time but with O(1) space.
  • đź§© pos parameter clarification:
    In LeetCode’s problem definition:
    “Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.”

    In this visualization, however, pos is passed as an input argument — but it serves only to help the input utility form the linked list by connecting the tail to the specified node. It is not part of the actual cycle detection algorithm logic.

Overview

We need to determine whether a singly linked list contains a cycle. A cycle exists if, while traversing via next pointers, we ever revisit the same node object again.

  1. Traverse the list starting from head with a pointer current.
  2. Maintain a Set named visited that stores node references we have already seen.
  3. For each step:
    • If current is already in visited, we have encountered the same node again → cycle detected (return true).
    • Otherwise, add current to visited and move to current = current.next.
  4. If we reach null, there is no cycle (return false).

Why This Works

In an acyclic list, each node is reached at most once, so we will eventually hit null. In a cyclic list, following next pointers should loop back to an already visited node. The check is done on the node objects themselves (references), not on their values.

Time Complexity

O(n) — where n is the number of nodes in the linked list. Each node (except the one where the cycle is detected, which will be encountered twice if a cycle exists) is visited at most once before we either detect a repeat or reach null.

Space Complexity

O(n) — where n is the number of nodes in the linked list. In the worst case (when there is no cycle), the visited set stores references to all n nodes.

Visucodize editorial solution titled JS Solution for LeetCode's Linked List Cycle coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/linked-list-cycle.