
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.
1function ListNode(val) {
2 this.val = val;
3 this.next = null;
4}
5
6var detectCycle = function(head) {
7 if (!head || !head.next) return null;
8 let slow = head, fast = head;
9 while (fast && fast.next) {
10 slow = slow.next;
11 fast = fast.next.next;
12 if (slow === fast) {
13 fast = head;
14 while (slow !== fast) {
15 slow = slow.next;
16 fast = fast.next;
17 }
18 return slow; // start of the cycle
19 }
20 }
21 return null; // no cycle
22};This JavaScript code uses a fast and slow pointer technique, similar to the other language solutions. The detectCycle function will return the start of the cycle, if exists, otherwise null.
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.
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.