You get head, the first node of a singly linked list. Return the node that sits in the middle of the list.
When the list has an even number of nodes there are two middle nodes; return the later of the two. The answer is the node itself, so it is shown as the list that starts there.
Example 1
Input: head = [7, 3, 9, 2, 5] Output: [9, 2, 5] Why: 9 has two nodes before it and two after
2 more examples and the constraints
Example 2
Input: head = [8, 1, 6, 4] Output: [6, 4] Why: 1 and 6 are both central; take the second, 6
Example 3
Input: head = [5] Output: [5] Why: a single node is its own middle
Constraints
- The list holds between 1 and 100 nodes
- Every node value is between 1 and 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count, then walk halfwayO(n)
- Fast and slow pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative pointer moves for 100 nodes | Verdict |
|---|---|---|---|
| Count, then walk halfway | O(n) | Passes; two passes | |
| Fast and slow pointers | O(n) | Best; one pass |
n = number of nodes. Both make about 1.5n pointer moves; the second makes them in a single pass, without knowing the length first.
Edge cases to test
- One node. [5]: fast.next is null at once, so slow stays on the head.
- Two nodes. [1, 2]: both are central, and the answer is the second, [2].
- Even length. [8, 1, 6, 4] returns the node 6, the later of the two middles.
- Odd length. [7, 3, 9, 2, 5] returns 9, with two nodes on each side.
Common mistakes
- Looping on
fast.next and fast.next.next, which returns the first middle on even lengths. - Checking only
fast.nextand then readingfast.next.nextwhen fast is already null. - Returning the value instead of the node; the caller expects the rest of the list from there.
How to talk through it
- 1Clarify. With an even count, do you want the first or the second middle? Is the list ever empty?
- 2Give the simple version. Count the nodes, then walk n // 2 steps from the head.
- 3Make it one pass. A pointer moving twice as fast reaches the end when the slow one is halfway.
- 4Code the loop. While fast and fast.next exist, slow takes one step and fast takes two; return slow.
- 5Test out loud. Run one node, two nodes and a five-node list.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?