Why this code doesn't work

  • 0

    I know the best answer is the fast and slow runner.

    But I can't figure out why this code won't pass.

    It works on my local machine (Python 3.4.1)

    class Solution:
        # @param head, a ListNode
        # @return a boolean
        def hasCycle(self, head):
            node = head
            while node:
                if node.next is head:
                    return True
            return False

    I got this result

    Time Limit Exceeded

    Last executed input: {3,2,0,-4}, tail connects to node index 1

  • 1

    Your code only works when the head itself is part of the cycle. However, for this problem, the cycle could begin anywhere in the linked list, and you have no idea where it starts. That's why a two-pointer technique is needed.

  • 0

    Oh ok,
    You are right.
    Thanks a lot.

Log in to reply

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