# 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)

##


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monica-granbois.gitbook.io/cs-theory-and-problems/problems/leetcode/141.-linked-list-cycle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
