Tutorialspoint
Problem
Solution
Submissions

Linked List has a Cycle

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

Write a C# program to determine if a linked list has a cycle in it. A cycle occurs when a node in the linked list points to a previously visited node, forming a loop.

Example 1
  • Input: head = [3, 2, 0, -4], pos = 1
  • Output: true
  • Explanation:
    • There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2
  • Input: head = [1, 2], pos = 0
  • Output: true
  • Explanation:
    • There is a cycle in the linked list, where the tail connects to the 0th node.
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
  • You must solve this problem without modifying the linked list structure
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Linked ListEYD. E. Shaw
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 (also known as the "tortoise and hare" approach)
  • Use two pointers moving at different speeds
  • If there is a cycle, the fast pointer will eventually meet the slow pointer
  • If there is no cycle, the fast pointer will reach the end of the list

Steps to solve by this approach:

 Step 1: Handle edge cases: empty list or single node list cannot have cycles.
 Step 2: Initialize two pointers, slow and fast, both starting at the head.
 Step 3: Move the slow pointer one step at a time.
 Step 4: Move the fast pointer two steps at a time.
 Step 5: If there is a cycle, the fast pointer will eventually catch up to the slow pointer.
 Step 6: If there is no cycle, the fast pointer will reach the end of the list (null).
 Step 7: Return true if the pointers meet, false otherwise.

Submitted Code :