AlgoInsight

DSA problem

Middle of the Linked List

EasyFast and Slow PointersPattern: Fast and Slow Pointerstop150AmazonMicrosoftGoogleAppleBloomberg

Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes (i.e., the list has an even number of nodes), return the second middle node.

The naive way to solve this is in two passes. First walk the entire list once to count the total number of nodes n; then walk again n / 2 steps from the head to land on the middle. That is O(n) time but it scans the list twice — wasteful when the list is huge or stored on slow memory.

The elegant single-pass technique is the classic fast and slow pointer pattern. Both pointers start at the head; the slow pointer advances one step per iteration while the fast pointer advances two steps. Because fast moves at exactly twice the speed of slow, by the time fast walks off the end of the list, slow has covered only half of it — which is precisely the middle.

For a list of odd length, fast lands on the last node and slow lands on the single middle. For a list of even length, fast falls off the end after the last node and slow lands on the second of the two middles, which is exactly what the problem requires. The whole algorithm finishes in one O(n) pass with O(1) extra space.

Examples

Example 1
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The list has 5 nodes, so the single middle is at index 2 (value 3). The returned reference exposes the suffix [3,4,5].
Example 2
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: The list has 6 nodes, so there are two middles (indices 2 and 3, values 3 and 4). The problem asks for the second middle, so we return the node with value 4 and its suffix [4,5,6].
Example 3
Input: head = [1]
Output: [1]
Explanation: A single-node list is its own middle, so we return that node unchanged.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointersfast-slow-pointers

Browse all DSA problems