-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List Cycle II.py
53 lines (38 loc) · 1.05 KB
/
Linked List Cycle II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Time Complexity - O(N)
#Space complexity - O(N)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
set_ = set()
ptr = head
while ptr:
if ptr in set_:
return ptr
set_.add(ptr)
ptr = ptr.next
return None
# Time Complexity - O(N)
#Space complexity - O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
break
else:
return None
while head != slow:
slow = slow.next
head = head.next
return head