Find the middle in one pass
EasyStuck?
Show a hintHide the hint
Move one reference one step and another two steps. When the fast one reaches the end, the slow one is at the middle.
The ideas behind this problem
Last problem in this lesson
Go to the next lessonReturn the middle node of a linked list, and everything after it. When there are two middles, return the second.
Worked example#
For 1 -> 2 -> 3 -> 4 -> 5, the middle is 3, so the answer is 3 4 5.
For 1 -> 2 -> 3 -> 4 -> 5 -> 6 there are two middles, 3 and 4, and the rule says take the second, so the answer is 4 5 6.
Doing it without counting first#
The obvious way is two passes: count the nodes, then walk half of them. That works, and there is a neater way that needs only one.
Move two references at different speeds. The slow one takes one step at a time, the fast one takes two. When the fast one runs off the end, the slow one is exactly halfway.
| step | slow | fast |
|---|---|---|
| start | 1 | 1 |
| 1 | 2 | 3 |
| 2 | 3 | 5 |
| 3 | fast is off the end, so slow is the answer |
It works because the fast reference covers twice the distance, so when it has covered all n nodes the slow one has covered n / 2.
The loop condition is where this goes wrong. You need fast and fast.next, because the step ahead reads fast.next.next. Checking only fast crashes on a list of even length.
Why it matters beyond this problem#
The same pair of speeds detects a loop in a list: if there is one, the fast reference eventually laps the slow one and they meet. Being able to say something about a list's shape in one pass with no extra memory is the point of the technique.
The cost#
Time O(n), one pass. Memory O(1).
Constraints#
1 <= number of nodes <= 1000001 <= value <= 100
Input
head is a count then that many values.
Output
The middle node and everything after it, values separated by spaces.
Examples
Input
5 1 2 3 4 5
Output
3 4 5
Five nodes, so the middle is the third.
Input
6 1 2 3 4 5 6
Output
4 5 6
Six nodes have two middles, 3 and 4, and the rule takes the second.
Input
1 1
Output
1
A single node is its own middle.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.