AlgoTales · Roadmap

Finding middle

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

To find the middle of a chain you cannot jump by position, so you send two walkers: one takes a step at a time, the other two steps. When the fast one reaches the end, the slow one is standing in the middle. One pass, no counting.

Practical use cases

  • Web app: Splitting a work queue into two halves. A bulk-email job holds 10,000 addresses in a chain and you want two workers to handle half each. Counting first and then walking again takes two passes. With a slow and a fast walker you land on the middle in one pass and cut the chain there.
  • Web app: Show the median item of a sorted list. A price-comparison page shows the middle-priced offer from a list already sorted by price. When the list is stored as a chain, the two-walker method reaches that middle offer without counting every item first, which keeps the page quick when sellers add or remove offers all the time.
  • System: Merge sort and palindrome tests. Sorting a chain with merge sort starts by splitting it in half, which needs the middle. Checking if a chain reads the same both ways also begins by finding the middle so the second half can be reversed and compared.

The story: Two Cousins on the Lane

Grandpa Bhaskar lived in the middle house of a long lane, and nobody remembered the exact house number. "Aarav, bring the biscuits to my house," he said. Aarav's cousin Zoya asked: "But how many houses are there?" Nobody knew. And the lane was so foggy you could see only the house in front of you.

The obvious plan: walk to the end counting, say 9 houses, then walk back to house 5. Two walks. Mira had a better idea: "Zoya, you walk at normal speed. Aarav, you take two houses per step. When Aarav reaches the end of the lane, Zoya will have walked exactly half. She is standing at the middle!"

They tried it. Aarav sprinted on and reached the last house just as Zoya reached house 5. Grandpa Bhaskar waved from his window. No counting, no second walk.

This is the slow and fast pointer trick (some call them tortoise and hare) for finding the middle of a linked list in a single pass. A linked list cannot tell you its length without a walk, so a clever walker saves a whole trip. You will meet the same two walkers again when we hunt for cycles.

How to spot this problem, and where you need it

You hold a list that can only be walked from the front and you need its middle item or need to split it in half, without knowing its length in advance.

Signs you need it

  • The wording says "find the middle", "split into two halves", "median of a sorted chain" or "second half".
  • Your solution counts the length in one loop and walks again in another loop, and you suspect there is a one-pass way.
  • The list has no index access, such as a linked list or a stream you can read only forward.

Where to use it in a project

  • The splitting step of merge sort on chains or large job queues.
  • Dividing a backlog of tasks between two workers.
  • Palindrome checks on linked data and picking a representative middle item.

The solution

Start two pointers at the head. Move the slow one by one step and the fast one by two steps at each round. When the fast pointer reaches the end (or has no next), the slow pointer is at the middle. For a clean split, stop one step earlier and cut the link there. It needs a single pass and just two variables.

Payoff: Before: two passes (count, then walk). After: one pass, with the middle in hand when the loop ends.

Explain it like I am 8

Two friends run along a path. One runs, the other zooms at double speed. When the zoomer reaches the finish line, the slow runner is halfway there. That is the middle!

How it works, step by step

  1. Set slow = head and fast = head.
  2. While fast and fast.next both exist: move slow one step and fast two steps.
  3. When the loop ends, slow is at the middle.
  4. For an odd length there is one middle. For an even length this loop gives the second of the two middles.
  5. Want the first middle for even lengths? Start with fast = head.next instead.

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;
    public function __construct($val, ?Node $next = null) { $this->val = $val; $this->next = $next; }
}
function fromArray(array $vals): ?Node {
    $head = null;
    foreach (array_reverse($vals) as $v) { $head = new Node($v, $head); }
    return $head;
}

// returns the middle node (the second middle when the length is even)
function middle(?Node $head): ?Node {
    $slow = $head;
    $fast = $head;
    while ($fast !== null && $fast->next !== null) {
        $slow = $slow->next;            // one step
        $fast = $fast->next->next;      // two steps
    }
    return $slow;
}

echo "Odd list  A B C D E -> middle is " . middle(fromArray(['A', 'B', 'C', 'D', 'E']))->val . "\n";   // C
echo "Even list A B C D   -> middle is " . middle(fromArray(['A', 'B', 'C', 'D']))->val . "\n";        // C
echo "Single node Z       -> middle is " . middle(fromArray(['Z']))->val . "\n";                      // Z

JavaScript

class Node {
  constructor(val, next = null) { this.val = val; this.next = next; }
}
function fromArray(vals) {
  let head = null;
  for (let i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
  return head;
}

// returns the middle node (the second middle when the length is even)
function middle(head) {
  let slow = head;
  let fast = head;
  while (fast !== null && fast.next !== null) {
    slow = slow.next;             // one step
    fast = fast.next.next;        // two steps
  }
  return slow;
}

console.log('Odd list  A B C D E -> middle is ' + middle(fromArray(['A', 'B', 'C', 'D', 'E'])).val);   // C
console.log('Even list A B C D   -> middle is ' + middle(fromArray(['A', 'B', 'C', 'D'])).val);        // C
console.log('Single node Z       -> middle is ' + middle(fromArray(['Z'])).val);                      // Z

Java

public class Main {
    static class Node {
        String val;
        Node next;
        Node(String val, Node next) { this.val = val; this.next = next; }
    }

    static Node fromArray(String[] vals) {
        Node head = null;
        for (int i = vals.length - 1; i >= 0; i--) { head = new Node(vals[i], head); }
        return head;
    }

    // returns the middle node (the second middle when the length is even)
    static Node middle(Node head) {
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;             // one step
            fast = fast.next.next;        // two steps
        }
        return slow;
    }

    public static void main(String[] args) {
        System.out.println("Odd list  A B C D E -> middle is " + middle(fromArray(new String[]{"A", "B", "C", "D", "E"})).val);   // C
        System.out.println("Even list A B C D   -> middle is " + middle(fromArray(new String[]{"A", "B", "C", "D"})).val);        // C
        System.out.println("Single node Z       -> middle is " + middle(fromArray(new String[]{"Z"})).val);                      // Z
    }
}

Go

package main

import "fmt"

type Node struct {
	val  string
	next *Node
}

func fromSlice(vals []string) *Node {
	var head *Node
	for i := len(vals) - 1; i >= 0; i-- {
		head = &Node{val: vals[i], next: head}
	}
	return head
}

// middle returns the middle node (the second middle when the length is even).
func middle(head *Node) *Node {
	slow, fast := head, head
	for fast != nil && fast.next != nil {
		slow = slow.next      // one step
		fast = fast.next.next // two steps
	}
	return slow
}

func main() {
	fmt.Println("Odd list  A B C D E -> middle is", middle(fromSlice([]string{"A", "B", "C", "D", "E"})).val) // C
	fmt.Println("Even list A B C D   -> middle is", middle(fromSlice([]string{"A", "B", "C", "D"})).val)      // C
	fmt.Println("Single node Z       -> middle is", middle(fromSlice([]string{"Z"})).val)                     // Z
}

Time: O(n) · Extra space: O(1). One pass, two pointers, no extra memory, compared with a first pass to count and a second pass to walk half.

Watch out for

  • Checking only fast.next and not fast itself: with an even length fast becomes null and the code crashes.
  • Forgetting that even-length lists have two middles; decide which one you want (the usual loop gives the second).
  • Counting nodes first, then walking again. That works, but misses the point of doing it in one pass.

Quick check

  1. When fast reaches the end, where is slow?
    • At the head
    • At the end too
    • At the middle
    • Beyond the end
  2. For the list A B C D, which node does the standard loop return?
    • B
    • C
    • D
    • A
  3. What is the loop condition?
    • while (slow !== null)
    • while (fast.next === null)
    • while (slow !== fast)
    • while (fast !== null && fast.next !== null)