Tutorialspoint
Problem
Solution
Submissions

Detect Cycle in Linked List

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to determine if a linked list has a cycle in it. A cycle occurs when a node in the linked list points back to a previously visited node, creating a loop. Use Floyd's Cycle Detection Algorithm (Tortoise and Hare) to solve this efficiently.

Example 1
  • Input: head = [3,2,0,-4], pos = 1
  • Output: true
  • Explanation:
    • The linked list contains nodes with values [3,2,0,-4].
    • The last node (-4) points back to the node at index 1 (value 2).
    • This creates a cycle: 3 → 2 → 0 → -4 → 2 (back to index 1).
    • Therefore, the linked list has a cycle.
Example 2
  • Input: head = [1,2], pos = -1
  • Output: false
  • Explanation:
    • The linked list contains nodes with values [1,2].
    • The pos = -1 indicates there is no cycle.
    • The last node (2) points to null, ending the list.
    • Therefore, the linked list does not have a cycle.
Constraints
  • The number of nodes in the list is in the range [0, 10^4]
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index in the linked-list
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Linked ListControl StructuresGoldman SachsPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers: a slow pointer (tortoise) and a fast pointer (hare)
  • Move the slow pointer one step at a time and the fast pointer two steps at a time
  • If there's no cycle, the fast pointer will reach the end (null) first
  • If there's a cycle, the fast pointer will eventually meet the slow pointer
  • Continue the loop until either the fast pointer reaches null or both pointers meet

Steps to solve by this approach:

 Step 1: Initialize two pointers (slow and fast) both pointing to the head of the linked list.

 Step 2: Move the slow pointer one step forward and the fast pointer two steps forward in each iteration.
 Step 3: Check if the fast pointer or fast.next becomes null, indicating no cycle exists.
 Step 4: If the slow pointer and fast pointer meet at the same node, a cycle is detected.
 Step 5: Continue the process until either a cycle is found or the fast pointer reaches the end.
 Step 6: Return true if cycle is detected, false otherwise.
 Step 7: Handle edge cases where the linked list is empty or has only one node.

Submitted Code :