Tutorialspoint
Problem
Solution
Submissions

If LinkedList Has Cycle

Certification: Basic Level Accuracy: 71.43% Submissions: 7 Points: 5

Write a Java program to determine if a linked list has a cycle in it. A cycle occurs when a node in a linked list points to a previous node, creating a loop. Return true if there is a cycle in the linked list, otherwise return false.

Example 1
  • Input: head = [3,2,0,-4], pos = 1
  • Output: true
  • Explanation:
    • Tail node connects to the node at index 1 → cycle exists
Example 2
  • Input: head = [1,2], pos = 0
  • Output: true
  • Explanation:
    • Tail node connects to the node at index 0 → cycle exists
Constraints
  • 0 ≤ number of nodes ≤ 10^4
  • -10^5 ≤ Node.val ≤ 10^5
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Linked ListEYPhillips
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 Floyd's Cycle-Finding Algorithm (Tortoise and Hare).
  • Use two pointers moving at different speeds.
  • If there's a cycle, the fast pointer will eventually meet the slow pointer.
  • If there's no cycle, the fast pointer will reach the end of the list.

Steps to solve by this approach:

 Step 1: Check if the list is empty or has only one node (no cycle possible).
 Step 2: Initialize two pointers, slow and fast, both starting at the head.
 Step 3: Move the slow pointer one step at a time and the fast pointer two steps at a time.
 Step 4: If there's a cycle, the fast pointer will eventually catch up to the slow pointer.
 Step 5: If the fast pointer reaches the end of the list (null), then there's no cycle.
 Step 6: Return true if the pointers meet, false otherwise.

Submitted Code :