Skip to content
LC-0141 Easy LeetCode

141. Linked List Cycle

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 52% Topics: Hash Table, Linked List, Two Pointers
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

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

Solution from kamyu104/LeetCode-Solutions · MIT