Skip to content

Commit 979a991

Browse files
committed
Add linked-list-cycle solution
1 parent 7bc13f3 commit 979a991

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

linked-list-cycle/Jeehay28.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
9+
/**
10+
* @param {ListNode} head
11+
* @return {boolean}
12+
*/
13+
14+
// Time Complexity: O(n)
15+
// Space Complexity: O(1)
16+
17+
// - In the worst case, we might traverse the entire linked list, but because the fast pointer moves at twice the speed of the slow pointer, they will meet within O(N) steps if a cycle exists.
18+
// - If there is no cycle, the fast pointer reaches the end in O(N) steps.
19+
// - Only two pointers (slow and fast) are used, which require O(1) extra space.
20+
// - No additional data structures (like arrays or hash sets) are used.
21+
22+
var hasCycle = function (head) {
23+
// If there is a cycle in the linked list, Floyd's Tortoise and Hare algorithm guarantees
24+
// that the fast and slow pointers will eventually meet.
25+
let fast = head;
26+
let slow = head;
27+
28+
while (fast && fast.next) {
29+
slow = slow.next; // Move slow pointer one step.
30+
fast = fast.next.next; // Move fast pointer two steps.
31+
32+
if (slow === fast) {
33+
return true; // Cycle detected.
34+
}
35+
}
36+
37+
return false;
38+
};
39+

0 commit comments

Comments
 (0)