Skip to content

Commit d3511b9

Browse files
committed
Sync LeetCode submission Runtime - 42 ms (71.73%), Memory - 19.6 MB (29.55%)
1 parent d9e0a71 commit d3511b9

File tree

1 file changed

+14
-26
lines changed

1 file changed

+14
-26
lines changed
Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
# Approach 2 - Floyd's Cycle Finding Algorithm
2-
3-
# Time: O(n), Space: O(1)
1+
# Approach 2: Floyd's Tortoise and Hare Algorithm
42

3+
# Time: O(n)
4+
# Space: O(1)
55

66
# Definition for singly-linked list.
77
# class ListNode:
@@ -10,32 +10,20 @@
1010
# self.next = None
1111

1212
class Solution:
13-
14-
def get_intersect(self, head):
15-
slow = head
16-
fast = head
17-
18-
while fast is not None and fast.next is not None:
13+
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
14+
slow = fast = head
15+
16+
while fast and fast.next:
1917
slow = slow.next
2018
fast = fast.next.next
19+
2120
if slow == fast:
21+
# Found intersection, find cycle start
22+
slow = head
23+
24+
while slow != fast:
25+
slow = slow.next
26+
fast = fast.next
2227
return slow
23-
2428
return None
25-
26-
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
27-
if head is None:
28-
return None
29-
30-
intersect = self.get_intersect(head)
31-
if intersect is None:
32-
return None
3329

34-
ptr1 = head
35-
ptr2 = intersect
36-
while ptr1 != ptr2:
37-
ptr1 = ptr1.next
38-
ptr2 = ptr2.next
39-
40-
return ptr1
41-

0 commit comments

Comments
 (0)