#876

Middle of the Linked List

Easy Fast & slow pointers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the middle node of a linked list; for an even number of nodes, return the second of the two middle nodes.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the middle node (second middle for even length).

Why this works: fast moves 2 steps while slow moves 1; when fast reaches the end, slow is halfway.

Example: 1 → 2 → 3 → 4 → 5

slow 1, fast 1 → slow 2, fast 3 → slow 3, fast 5 → stopmiddle 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using the loop condition fast.next.next != null, which returns the first middle for even lengths.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Linked List
🎬 Episodes 40–45: video coming soon