> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Linked List Cycle II Python Solution

> Tested Python solution for LeetCode 142 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 142, Medium. Topics: Hash Table, Linked List, Two Pointers. [View on LeetCode](https://leetcode.com/problems/linked-list-cycle-ii/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 142   # by problem number
lcpy gen -s linked_list_cycle_ii   # by problem name
```

## Problem

Given the `head` of a linked list, return the node where the cycle begins. If there is no cycle, return `null`.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png)

```
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
```

![Example 2](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png)

```
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
```

![Example 3](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png)

```
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
```

### Constraints

* The number of the nodes in the list is in the range \[0, 10^4].
* -10^5 \<= Node.val \<= 10^5
* pos is -1 or a valid index in the linked-list.

**Follow up:** Can you solve it using O(1) (i.e. constant) memory?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/linked_list_cycle_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/linked_list_cycle_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import ListNode


class Solution:
    # Time: O(n)
    # Space: O(1)
    def detect_cycle(self, head: ListNode[int] | None) -> ListNode[int] | None:
        if not head:
            return None

        slow: ListNode[int] | None = head
        fast: ListNode[int] | None = head

        # Phase 1: Detect if cycle exists using Floyd's algorithm
        has_cycle = False
        while fast and fast.next:
            assert slow is not None
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                has_cycle = True
                break

        if not has_cycle:
            return None

        # Phase 2: Find the start of the cycle
        slow = head
        assert fast is not None  # fast is guaranteed to be a valid node here
        while slow is not fast:
            assert slow is not None
            slow = slow.next
            assert fast.next is not None
            fast = fast.next

        return slow
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(1)  |

## Tags

[AlgoMaster 75](/catalog/algo-master-75).
