class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return False
isVisited = {}
while head:
if head in isVisited:
return True
else:
isVisited[head] = True
head = head.next
return False
Time Complexity: O(N)
Space Complexity: O(N)
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return False
ptrSlow, ptrFast = head, head.next
while ptrFast != None and ptrFast.next != None:
ptrSlow = ptrSlow.next
ptrFast = ptrFast.next.next
if ptrSlow == ptrFast:
return True
return False
Time Complexity: O(N)
Space Complexity: O(1)