# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: if not head: return False prev = None orig_head = head while head.next is not None: tmp = head.next if tmp == orig_head: return True # Reverse the direction as we traverse the nodes # If a cycle exists in original list, then we'll # eventually travel back to the original head head.next = prev prev = head head = tmp return False Complexity Time: O(n) — We’d be travelling to and fro throughout the list in the worst case Space: O(1)