Task example: Middle of the Linked List

Find the middle node of a nonempty singly linked list. If its length is even, choose the second middle node. Return the original node with its remaining chain; leave all values and links unchanged.

Example 1
Input
head = [1,2,3,4,5,6]
Output
node 4 → [4,5,6]

Array notation shows node values. The editor supplies ListNode with val and next. Your function receives a head node and must return a node, not an array or a copied chain.

LeetCode 876
01 / Count & walk - two passes

Count & walk: video explanation

head = [1,2,3,4,5,6]
result = node 4 → [4,5,6]

Prefer reading? Follow the steps below.

  1. Walk from head to None, counting every node. Keep the original head so you can start again.
  2. Reset current to head. Move count // 2 links. Node positions start at zero, so six nodes require three moves to reach the fourth node.
  3. Return current itself. Five nodes lead to the third node; six lead to the fourth. No nodes are created and no links are changed.

Time complexity · O(n)

Counting visits n nodes; the second pass follows floor(n / 2) links. Their sum is O(n), not O(n²).

Space complexity · O(1)

A counter and a fixed number of node references use O(1) extra space.

PYTHONLive code trace
02 / Slow & fast pointers - one pass

Slow & fast pointers: video explanation

head = [1,2,3,4,5,6]
result = node 4 → [4,5,6]

Prefer reading? Follow the steps below.

  1. Start slow and fast at head. Continue only while fast and fast.next both exist; this makes the two-link move safe.
  2. Move slow one link and fast two links. After k iterations, slow has moved k links and fast has moved 2k links.
  3. When fast reaches None or has no next node, return slow. Starting both at head selects the second middle for an even length.

Both approaches already use O(n) time and O(1) extra space. Slow and fast pointers avoid counting and restarting, finding the middle in one pass.

Time complexity · O(n)

The loop runs floor(n / 2) times, with constant work each time: O(n) time.

Space complexity · O(1)

Only slow and fast references are needed. No array, recursion stack, or replacement nodes: O(1) extra space.

PYTHONLive code trace

Middle of the Linked List · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.