Data Structures · Visualization
Linked List: Find Middle
Linked List
Finding the middle node without knowing the length in advance uses the 'slow and fast pointer' trick: one pointer moves one step at a time while another moves two steps at a time. Time: O(n). Space: O(1).
Big-O: Lookup O(n); insert/delete at head O(1).
Linked List: Find Middle
Linked ListFinding the middle node without knowing the length in advance uses the 'slow and fast pointer' trick: one pointer moves one step at a time while another moves two steps at a time. When the fast pointer reaches the end, the slow pointer is exactly at the middle, because it has covered half the distance.
How Find Middle Works
- Set both slow and fast pointers to the head.
- Move slow forward by one node and fast forward by two nodes at the same time.
- Repeat while fast and fast.next are not null.
- When fast can no longer move two steps, slow is at the middle node.
Find Middle Worked Example
Input: head -> 1 -> 2 -> 3 -> 4 -> 5 -> null
- slow=1, fast=1
- slow=2, fast=3
- slow=3, fast=5
- fast.next is null, stop. Middle = slow = 3
Output: Middle node value: 3
Press ▶ Run to watch it step by step.
def find_middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next # 1 step
fast = fast.next.next # 2 steps
return slow # middle node
# slow ends exactly at the middle
# example: find middle on [1, 2, 3, 4, 5]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Find Middle Time & Space Complexity
When to Use Find Middle
- Splitting a list in half for merge sort on linked lists
- Finding the median element without counting the list twice
- A building block for palindrome-checking on linked lists
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.