Middle of the Linked List DSA Solution - Study Chapter | QuizMaker

Middle of the Linked List explained with brute force, optimized fast/slow pointers, dry run, edge cases, complexity, and Python, C++, Java code.

Read
9m
Type
Chapter
Access
Free

Course

DSA Course: Interview Patterns and Problem Solving

Topic

Module 5: Linked List

Learning Outcome

After this lesson, you should be able to use fast and slow pointers to find the middle node in one pass.

Problem Statement

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

InputOutputWhy
1 -> 2 -> 3 -> 4 -> 533 is the middle node.
1 -> 2 -> 3 -> 4 -> 5 -> 64There are two middles, so return the second.

Brute Force Approach

Count the number of nodes, then walk again to index n / 2.

This is correct, but it needs two passes through the list.

Optimized Approach

Move slow one step and fast two steps. When fast reaches the end, slow has moved half as many steps, so it is at the middle.

Exact Pseudocode

slow = head
fast = head
while fast is not null and fast.next is not null:
  slow = slow.next
  fast = fast.next.next
return slow

Reference Code

class Solution:
    def middleNode(self, head):
        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

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

        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }

        return slow;
    }
};
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        return slow;
    }
}

Sample Dry Run

StepslowfastMeaning
Start11Both at head
123Fast moved twice as far
235Slow reaches middle
Stop3null after next move checkReturn slow

Complexity

MeasureValueReason
TimeO(n)The list is traversed once.
SpaceO(1)Only two pointers are used.

Edge Cases

Interview Checklist

FAQs

Why does slow end at the middle?

Because fast moves twice as quickly. When fast covers the full list, slow covers half.

Why does this return the second middle for even length?

The loop continues while fast can move two steps, causing slow to advance to the second middle.

What is the core pattern?

Fast and slow pointers.

Tags

Open on QuizMaker