The Floyd's Tortoise and Hare algorithm is a two-pointer technique that is used to detect cycles in a linked list. The approach involves using two pointers, one moving twice as fast as the other. If there's a cycle, the fast pointer will eventually meet the slow pointer. This method works in O(n) time with O(1) space.
Time Complexity: O(n), where n is the number of nodes in the list.
Space Complexity: O(1), constant space usage.
1function ListNode(val) {
2 this.val = val;
3 this.next = null;
4}
5
6var hasCycle = function(head) {
7 let slow = head, fast = head;
8 while (fast && fast.next) {
9 slow = slow.next;
10 fast = fast.next.next;
11 if (slow === fast) return true;
12 }
13 return false;
14};
The JavaScript function leverages the same logic of two pointers. Different speeds of traversal will determine if a cycle exists when the pointers align.
This approach uses a HashSet to track the nodes visited during the traversal. If a node is encountered twice, there is a cycle. This method requires O(n) space but is simpler to understand.
Time Complexity: O(n^2) because of nested loops (non-optimal use of memory).
Space Complexity: O(n), where n is the number of nodes (uses additional storage).
1using System.Collections.Generic;
2
3public class ListNode {
4 public int val;
5 public ListNode next;
6 public ListNode(int x) {
7 val = x;
8 next = null;
9 }
10}
11
12public class Solution {
13 public bool HasCycle(ListNode head) {
14 HashSet<ListNode> visited = new HashSet<ListNode>();
15 while (head != null) {
16 if (visited.Contains(head)) return true;
17 visited.Add(head);
18 head = head.next;
19 }
20 return false;
21 }
22}
The C# solution follows a logical pattern applying HashSet to track all encountered nodes. Cycle detection occurs when a node reappears in the set.