
Sponsored
Sponsored
The Floyd's Cycle Detection Algorithm, also known as the tortoise and hare algorithm, is well-suited for detecting cycles in a linked list.
In this approach, two pointers (slow and fast) are initiated. The slow pointer moves one step at a time, while the fast pointer moves two steps. If a cycle is present, the fast pointer will meet the slow pointer within the cycle. Once a cycle is detected, reset one pointer to the head of the linked list and keep the other pointer at the meeting point. Move both pointers one step at a time; the node where they meet again is the cycle's start.
Time Complexity: O(n) - The list is traversed twice at most.
Space Complexity: O(1) - No additional space apart from pointers.
1class ListNode {
2 int val;
3 ListNode next;
4 ListNode(int x) {
5 val = x;
6 next = null;
7 }
8}
9
10public class Solution {
11 public ListNode detectCycle(ListNode head) {
12 if (head == null || head.next == null) return null;
13 ListNode slow = head, fast = head;
14 while (fast != null && fast.next != null) {
15 slow = slow.next;
16 fast = fast.next.next;
17 if (slow == fast) {
18 fast = head;
19 while (slow != fast) {
20 slow = slow.next;
21 fast = fast.next;
22 }
23 return slow;
24 }
25 }
26 return null;
27 }
28}The Java solution defines a ListNode class and a detectCycle method in the Solution class. It relies on the same two-pointer technique where slow and fast pointers check for cycles. If a cycle is detected, the method resets one pointer to head and determines the start of the cycle as they move synchronously.
This approach involves using a hash table (or set) to record visited nodes. Traverse the linked list, and for each node, check if it has already been seen (exists in the hash set). If it has, a cycle is detected that starts at this node. If the end of the list is reached without seeing any node twice, the list does not contain a cycle.
Though this technique uses extra space for the data structure, it can be easier to implement and understand.
Time Complexity: O(n) - each node is visited once.
Space Complexity: O(n) - for the hash table.
1
This C solution creates a hash table, inserting each visited node with a hashed pointer as the key. If a node is found in the table during traversal, it's part of the cycle's start and returned. Otherwise, the list is acyclic.