> For the complete documentation index, see [llms.txt](https://monica-granbois.gitbook.io/cs-theory-and-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://monica-granbois.gitbook.io/cs-theory-and-problems/problems/leetcode/141.-linked-list-cycle.md).

# 141. Linked List Cycle

## Description

See: <https://leetcode.com/problems/linked-list-cycle/>

## Solution

The strategy is to use two pointers, a walker and a runner (slow and fast). The walker (slow) moves forward one node at a time. The runner (fast) moves ahead 2 nodes at a time. So if there is a cycle, the runner will eventually lap the walker and the walker and runner will be at the same node. Otherwise the runner will reach the end of the linked list first.

```python
# 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 or not head.next:
            return False
        walker = head
        runner = head
        while runner and runner.next:
            walker = walker.next
            runner = runner.next.next
            if walker == runner:
                return True
        return False
    
```

Time Complexity: O(N).&#x20;

Space complexity O(1)

##
