Fastest (80 ms) Python O(n) time O(1) space solution


  • 0
    L

    Same hare-tortoise algorithm with slightly different implementation.

    class Solution(object):
            def detectCycle(self, head):
                if not head or not head.next:
                    return None
                slow,fast = head,head.next
                while fast and fast.next:
                    slow = slow.next
                    fast = fast.next.next
                    if slow == fast:
                        # there is a cycle
                        slow = slow.next
                        p = head
                        while p != slow:
                            p = p.next
                            slow = slow.next
                        return p
                return None

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.