Middle of the Linked List
Return the middle node of a linked list in one pass: a fast pointer moves two steps for every one of slow.
The problem
You get the head of a singly linked list. Return its middle node. When the list has an even number of nodes there are two middle nodes, and you return the second one. The examples show the answer as the list that starts at the returned node.
Input head = [4, 8, 15, 16, 23]
Output [15, 16, 23]
With five nodes, the third node (15) is the middle, and the list from there reads 15, 16, 23.
Input head = [3, 6, 9, 12]
Output [9, 12]
With four nodes, the two middle nodes are 6 and 9, and you return the second one.
Key constraint: For an even length you must return the second of the two middle nodes, which decides exactly when the loop stops.
How to spot the pattern
- You need a position that depends on the length of the list, like the middle, without knowing the length.
- A singly linked list has no index access, so you can't jump straight to position n / 2.
The idea
Move two pointers from the head: slow takes one step at a time and fast takes two. When fast runs out of list, slow has walked exactly half as far, so it stands at the middle. Stopping as soon as fast or fast.next is null makes slow land on the second middle node when the length is even.
Brute force: Copy the nodes into an array and return the one at index n / 2, which takes O(n) extra space.
Step by step
- 1Start
slowandfastathead. - 2While
fastandfast.nextare both not null, moveslowone node andfasttwo nodes. - 3Return
slow.
See the pattern move
The fast and slow pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next # one step
fast = fast.next.next # two steps
return slowComplexity
Time
O(n)
Space
O(1)
fast reaches the end after about n / 2 rounds, and only two pointers are stored.
Watch out for
- Looping while
fast.nextandfast.next.nextexist, which stops one round early and returns the first middle node for even lengths. - Checking
fast.nextbefore checkingfast, which crashes oncefasthas become null.
Follow-up questions
How would you return the first middle node instead?
Loop while fast.next and fast.next.next exist, so slow stops one node earlier on even lengths. Reorder List and Palindrome Linked List use this version to find the end of the first half.
How would you delete the middle node?
Start fast two nodes ahead (at head.next.next) so that slow stops on the node just before the middle, then link it past the middle with slow.next = slow.next.next. Handle a one-node list separately.
In Hinglish
Tez pointer do kadam chalta hai, dheema ek kadam. Tez wala end par pahunche tab dheema bilkul beech mein khada hoga.