Skip to problem
←

Linked List Cycle

Easy 0 attempts

Given the head of a singly linked list, return true if repeatedly following next pointers revisits the same node object. Return false if traversal reaches null, including when the list is empty.

Equal node values do not imply a cycle. For example, three distinct nodes with values [5,5,5] and a tail pointing to null are not cyclic. A single node whose next points to itself is cyclic.

Use O(1) extra space.

The examples encode the list as [values, pos]. If pos is not -1, the last node points back to the node at that zero-based index. Your function receives only head, not the array or pos.

Function contract

Implement linkedListCycle(head). headFixture is [values, pos]; the tail links to the zero-based pos, or null when pos is -1. The function receives only the head.

Output: Return true if following next pointers revisits the same node object; otherwise return false.

Example 1

Input
headFixture = [[3,2,0,-4],1]
Output
true

Example 2

Input
headFixture = [[1],-1]
Output
false
Visual Aid
A cycle follows links, not repeated values
Linked list with a cycle starting at index oneFour nodes contain 3, 2, 0, and minus 4. Arrows connect consecutive nodes. A return arrow connects minus 4 back to 2.320−4head · 0index 1index 2index 3tail.next → index 1

For [[3,2,0,-4],1], the last node links back to index 1. Following next visits 2 → 0 → −4 → 2 repeatedly.

Constraints
  • 0 to 10^4 nodes
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid zero-based node index; an empty list uses pos = -1

Approach: Floyd's Tortoise and Hare

Use two pointers: slow moves one step at a time, fast moves two steps. If the list has a cycle, the fast pointer will eventually meet the slow pointer. If fast reaches null, there is no cycle.

javascript
function linkedListCycle(head) {
  let slow = head, fast = head;
  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}

Time Complexity: O(n)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript