Tensorum
LeetCode 876 · Basics

Middle of the Linked List

LeetCode 876 · Easy · solution, intuition & step-by-step walkthrough

Slow / fast pointers.

EasyLinked ListTwo Pointers
0 msruntime · beats 100%
17.9 MBmemory · beats 100%
1approach
6accepted runs · last 4 Jan 2025

This is how I solved Middle of the Linked List (LeetCode 876), an easy problem from the Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Move one pointer a step at a time and another two steps at a time. When the fast pointer runs off the end, the slow one is in the middle.

Approach

  1. 1

    slow = fast = head.

  2. 2

    While fast and fast.next: slow one step, fast two.

  3. 3

    Return slow (the second middle for even lengths).

How I solved it

Tortoise and harePythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow =fast= head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow
Loading the step-through…

Middle of the Linked List — FAQ

What is the intuition behind Middle of the Linked List?

Move one pointer a step at a time and another two steps at a time. When the fast pointer runs off the end, the slow one is in the middle.

How do you solve Middle of the Linked List (LeetCode 876)?

1. slow = fast = head. 2. While fast and fast.next: slow one step, fast two. 3. Return slow (the second middle for even lengths).

What is the time and space complexity of Middle of the Linked List?

Time: O(n). Space: O(1). (Accepted approach: Tortoise and hare.)

What are common mistakes in Middle of the Linked List?

The loop condition decides first vs second middle.