Skip to main content

Middle of the Linked List

Problem Statement:​

Given theΒ headΒ of a singly linked list, returnΒ the middle node of the linked list.

If there are two middle nodes, returnΒ the second middleΒ node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

  • Example:



βœ… Solution: Two Pointers (Tortoise-Hare)​

class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head;
ListNode *fast = head;

// Move fast by 2 and slow by 1 step
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}

// When fast reaches end, slow is at middle
return slow;
}
};


πŸ“ How It Works​

  • We use two pointers:
    • slow moves one node at a time.
    • fast moves two nodes at a time.
  • When fast reaches the end, slow will be at the middle node.
  • In case of even-length list, this returns the second middle node.

This is also called the Tortoise-Hare algorithm.


🧩 Key Formula / Transition​

  • slow = slow->next
  • fast = fast->next->next

This ensures slow reaches halfway when fast finishes the list.


⏱️ Time & Space Complexity​

MetricValue
TimeO(N)
SpaceO(1)

Only one traversal, and no extra space.


⚠️ Edge Cases​

  • List is empty β†’ returns NULL
  • List has one node β†’ returns that node
  • List has even number of nodes β†’ returns second middle (as required by LeetCode)

πŸ’‘ Other Approaches​

ApproachTimeSpaceNotes
Count & TraverseO(N)O(1)First pass to count nodes, second to reach middle
Store in vectorO(N)O(N)Simplest but extra space

  • Detect Cycle in Linked List (uses same fast/slow logic)
  • Find the N-th node from end
  • Reverse a Linked List
  • Palindrome Linked List (use middle to compare halves)

πŸš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→