Linked listsAnimated
Find Middle of Linked List
When the fast pointer reaches the end the slow one is at the middle.
Time
O(n)
Extra space
O(1)
Use it for
Splitting lists in half.
How it works
- Move a slow pointer 1 step and a fast pointer 2 steps at a time.
- When fast reaches the end, slow has moved half as far: it is at the middle.
- For an even length it lands on the second of the two middle nodes.
- One pass, O(n), no need to know the length first.
Watch it run
Loading animation…