Middle of the Linked List

Easy

Topics
Linked ListTwo Pointers

Given the head of a singly linked list, return the list starting from the middle node. If there are two middle nodes, return the second one.

Example 1

1slow/fast2345null
The answer is index 2.
Linked list values from head to tail.
Input:  head = [1,2,3,4,5]
Output: [3,4,5]

Example 2

1slow/fast23456null
Input:  head = [1,2,3,4,5,6]
Output: [4,5,6]

Constraints

  • 1 <= number of nodes <= 100
  • 1 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Without a length, the obvious route is two passes: count the nodes, then walk half of them. That works and is O(n) time, O(1) space.

One pass is possible with the tortoise and hare: advance one pointer by a single node and another by two. When the fast pointer runs off the end, the slow one has covered exactly half the distance, so it is standing on the middle.

The loop condition decides which middle you get when the length is even. With while fast and fast.next the slow pointer ends on the second of the two middle nodes, which is what this problem asks for. Using while fast.next and fast.next.next stops a step earlier and yields the first — worth knowing, because the sibling problem (delete the middle, find a cycle start) wants the other one.

Approach

  1. slow = fast = head.
  2. While fast and fast.next exist: slow advances one, fast advances two.
  3. Return slow.

Dry Run

1 -> 2 -> 3 -> 4 -> 5        odd length

start      slow=1  fast=1
step       slow=2  fast=3
step       slow=3  fast=5
fast.next is null -> stop
answer node 3   ✓

1 -> 2 -> 3 -> 4 -> 5 -> 6   even length

start      slow=1  fast=1
step       slow=2  fast=3
step       slow=3  fast=5
step       slow=4  fast=null
answer node 4   (the second middle, as required)

Complexity

  • Time — O(n): the fast pointer traverses the list once; the slow one covers half.
  • Space — O(1): two pointers. Collecting nodes into an array and indexing the middle is O(n) space for the same answer.

Common Pitfalls

  • Checking only fast and dereferencing fast.next.next unguarded, which null-dereferences on an even-length list.
  • Using the other loop condition and returning the first middle. For an even length this problem wants the second.
  • Advancing both pointers in the wrong order, or advancing fast once per iteration, which returns the end rather than the middle.
  • Special-casing a single node. It falls out: the loop never runs and slow is still head.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def middleNode(self, head):
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow
Asked at Walmart Labs
SensAI
Beta
Tap the mic to stop voice mode