Delete the Middle Node of a Linked List

medium

You are given the head of a singly linked list. Delete the middle node of the list and return the head of the modified list.

For a list of size n, the middle node is the node at index ⌊n / 2⌋ using 0-based indexing — where ⌊x⌋ is the largest integer less than or equal to x.

Concretely, for n = 1, 2, 3, 4, 5 the middle indices are 0, 1, 1, 2, 2. So in a list of 7 nodes the middle is index 3; in a list of 4 nodes it is index 2.

Deleting the only node of a single-element list leaves an empty list, so you return an empty (null) head.

Hints

You must land on the node at index ⌊n/2⌋ — and to delete it in a singly linked list, what other node do you actually need a grip on?
One pointer moving twice as fast as another reaches the end in half the steps. Where is the slow one standing when the fast one stops?
Advance fast two steps and slow one step per loop, trailing slow with a prev pointer; when fast falls off the end, set prev.next = slow.next.

Common doubts

Because fast moves twice as far as slow. When fast has traveled the whole list of length n, slow has traveled n/2 — precisely index ⌊n/2⌋.
Its middle is index 0 — the node itself. Deleting it returns an empty (null) list, so guard this case before the loop.
Logically you only need to rewire prev.next past it. In languages with manual memory you may also free it; the judge only checks the resulting sequence of values.

Interview follow-ups

Give fast a k-step head start, then advance both until fast hits the end — slow lands on the target node's predecessor.
Same two speeds: if fast ever meets slow, there is a loop. This is Floyd's cycle-detection algorithm.

Fun facts

  • The two-speed idea is nicknamed the tortoise and the hare — the same racing metaphor Floyd used for his cycle-detection algorithm.
  • Finding the middle in one pass is the setup step for reversing the second half of a list, the standard trick for checking whether a linked list is a palindrome.

Asked at

AmazonMicrosoftGoogleMetaAdobe
Frequently Sometimes Occasionally
Example 1
Input: head = [1,3,4,7,1,2,6]
Output: [1,3,4,1,2,6]
n = 7, so the middle is index ⌊7/2⌋ = 3 (value 7). Removing it leaves [1,3,4,1,2,6].
Example 2
Input: head = [1,2,3,4]
Output: [1,2,4]
n = 4, so the middle is index ⌊4/2⌋ = 2 (value 3).
Example 3
Input: head = [2,1]
Output: [2]
n = 2, so the middle is index ⌊2/2⌋ = 1 (value 1). Only node 0 remains.
Constraints

- The number of nodes in the list is in the range [1, 10^5]. - 1 <= Node.val <= 10^5

Solve this problem →