Middle of the Parade

Easytwo pointersAlso known as Middle of the Linked List

A town parade is a line of floats. Each driver only knows which float is right behind them. Nobody has the full list, and nobody knows how long the parade is.

The TV crew wants to film from the float in the middle of the parade. Starting from the lead float and following "who is behind you" from float to float, find it.

Your task

Write middleFloat(head). head is the first node of a linked list (each node has val and next). Return the middle node.

With an odd number of floats there is one middle. With an even number there are two; return the second one. The tests read the list from the node you return to the end, so returning the middle node of [1, 2, 3, 4, 5] shows as [3, 4, 5].

middleFloat(head: ListNode) → ListNode

Examples

Example 1
Input
head = [8, 3, 6, 2, 9]
Output
[6, 2, 9]
Why

Five floats. The third, 6, has two floats ahead of it and two behind. From 6 the parade reads 6, 2, 9.

Example 2
Input
head = [8, 3, 6, 2]
Output
[6, 2]
Why

Four floats, so 3 and 6 are both in the middle. The rule picks the second one, 6. Returning 3 would show [3, 6, 2] and fail.

Constraints

  • 1 ≤ number of floats ≤ 10,000
  • Float ids are integers and may repeat.
  • Return a node from the list you were given; do not build a new list.
Start with brute force

Walk the whole parade once to count the floats, n. Then walk again from the start and stop after n / 2 steps (rounded down).

That is O(n) and perfectly correct, but it needs two full passes. The point of this problem is a trick that finds the middle in a single pass without knowing n, which is what you need when the list is being read once, like a stream, or as part of a bigger list algorithm.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code