Advertisement
DeepRest

Linked List Cycle II

Jan 18th, 2022 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. '''
  2. First part
  3. Let the length of linear part of linked list be x and the circular part be y. So, when the slow pointer reaches tge start of cycle(i.e covered x+1 nodes), the fast pointer would be (x+1)%y distance ahead. This is becoz normally the fast pointer would have been x+1 nodes ahead but since fast pointer has already entered the cycle, the distance b/w them would be (x+1)%y.Thus, we can say that the slow pointer is y-x%y-1 ahead of fast pointer(clockwise). Since the relative speed of both pointer is 1x(2x of fp-1x of sp), this gap would reduce to zero in y-x%y-1 iterations and by this time slow pointer would have travelled y-x%y-1 nodes from cycle start. Thus fp==sp at y-x%y-1 nodes from cycle start(clockwise from cycle start) or we can say x%y+1 nodes from cycle start(Anticlockwise from cycle start)
  4. Sexond part
  5. Now we take two pointers p1, p2 one starting from head and other starting from sp.next(one node clockwise ahead of the meeting point of fp and sp).
  6. Thus when p1 advances x times, we can say that it travels q no. of y nodes and x%y nodes (q=floor(x/y)). Since p2 moves at same speed as p1 it also travels q no. of y nodes and x%y nodes. But since travelling any number of y nodes in the cycle brings us to our starting point(in this case one node ahead of where fp and sp had met), total effective nodes travelled is x%y from strating point of p2(clockwise), which is nothing but the starting point of cycle(as already shown in first part that starting point is x%y+1 nodes ahead of meeting point of fp and sp). Also p1 has reached the starting point of cycle (as by this time it has travelled x nodes). Thus meeting point of p1 and p2 is starting point of cycle.
  7. '''
  8. class Solution(object):
  9.     def detectCycle(self, head):
  10.         if not head:
  11.             return head
  12.         sp, fp = head, head.next
  13.         while fp is not None and fp.next is not None and sp != fp:
  14.             sp = sp.next
  15.             fp = fp.next.next
  16.         if sp == fp:
  17.             p1 = head
  18.             p2 = sp.next
  19.             while p1 != p2:
  20.                 p1 = p1.next
  21.                 p2 = p2.next
  22.             return p1
  23.         else:
  24.             return None
  25.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement