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

# Middle of the Linked List Python Solution

> Tested Python solution for LeetCode 876 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 876, Easy. Topics: Linked List, Two Pointers. [View on LeetCode](https://leetcode.com/problems/middle-of-the-linked-list/description/).

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

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

## Problem

Given the `head` of a singly linked list, return *the middle node of the linked list*.

If there are two middle nodes, return **the second middle** node.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg)

```
Input: head = [1,2,3,4,5]
Output: [3,4,5]
```

**Explanation:** The middle node of the list is node 3.

![Example 2](https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg)

```
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
```

**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.

### Constraints

* The number of nodes in the list is in the range `[1, 100]`.
* `1 <= Node.val <= 100`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/middle_of_the_linked_list/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/middle_of_the_linked_list/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 middle_node(self, head: ListNode[int] | None) -> ListNode[int] | None:
        slow = fast = head
        while fast and fast.next:
            assert slow is not None
            slow = slow.next
            fast = fast.next.next
        return slow
```

## Complexity

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

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [NeetCode All](/catalog/neetcode).
