File: middle-of-the-linked-list/solution.py

Date: 2026-06-06

Time: 17:49

Purpose

This file solves LeetCode 876 — Middle of the Linked List. It defines the ListNode data structure and a function that finds the middle node of a singly linked list using the slow/fast pointer (tortoise and hare) technique.

Key Components

ListNode

A minimal singly linked list node with two fields:

This class is the shared linked list definition across the repo — the "Imported By" list shows hundreds of test files reference it.

middleofthelinkedlist(head)

Contract: Given the head of a singly linked list, return the middle node. For even-length lists (two middle nodes), return the second one.

Patterns

Slow/fast pointer (tortoise and hare). Two pointers start at head. slow advances one step per iteration; fast advances two. When fast reaches the end, slow is at the midpoint. This is the canonical O(n) time, O(1) space approach for finding the middle of a linked list without knowing its length.

The loop condition while fast and fast.next handles both odd and even lengths:

Dependencies

Imports: Only standard library — annotations for PEP 604 forward-reference support, Optional from typing.

Imported by: This file is the canonical ListNode definition for the project. The massive "Imported By" list (300+ test files) is because test files across unrelated problems import ListNode from here to construct linked lists in their test fixtures. The function middleofthelinkedlist is only tested by middle-of-the-linked-list/test_solution.py.

Flow

1. Initialize slow and fast to head.

2. Each iteration: slow moves one node forward, fast moves two.

3. Loop exits when fast is None (even length) or fast.next is None (odd length).

4. Return slow — it now points to the middle node.

For a list 1 -> 2 -> 3 -> 4 -> 5:

| Step | slow | fast |

|------|------|------|

| 0 | 1 | 1 |

| 1 | 2 | 3 |

| 2 | 3 | 5 |

Loop exits (fast.next is None). Return node 3.

Invariants

Error Handling

None. The function assumes well-formed input (no cycles, valid ListNode instances). If the list contains a cycle, this function loops forever — but that's outside the problem's contract. No exceptions are raised or caught.

Topics to Explore

Beliefs