Skip to content

Commit 16148c5

Browse files
committed
Time: N/A (0%), Space: N/A (0%) - LeetHub
1 parent 598a82f commit 16148c5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import Optional
4+
5+
6+
class ListNode:
7+
def __init__(self, x):
8+
self.val = x
9+
self.next = None
10+
11+
12+
class Solution:
13+
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
14+
nodeSeen = set()
15+
node = head
16+
while node:
17+
if node in nodeSeen:
18+
return node
19+
nodeSeen.add(node)
20+
node = node.next
21+
return None
22+
23+
# time complexity: O(n)
24+
# space complexity: O(1)
25+
class Solution:
26+
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
27+
slow = head
28+
fast = head
29+
30+
while fast and fast.next:
31+
slow = slow.next
32+
fast = fast.next.next
33+
34+
if slow == fast:
35+
break
36+
37+
if not fast or not fast.next:
38+
return None
39+
40+
fast = head
41+
42+
while slow != fast:
43+
slow = slow.next
44+
fast = fast.next
45+
46+
return slow
47+
48+
head = ListNode(3)
49+
head.next = ListNode(2)
50+
head.next.next = ListNode(0)
51+
head.next.next.next = ListNode(-4)
52+
head.next.next.next.next = head.next
53+
print(Solution().detectCycle(head))

0 commit comments

Comments
 (0)