Skip to content
LEETFLIX

Middle of the Linked List

Solve on LeetCode

Easy · slow / fast middle. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 876. Middle of the Linked List. The copyrighted prompt is on LeetCode. This page is a working slow / fast middle for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

head =
[1, 2, 3, 4, 5]

Output

[3, 4, 5]

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Fast reaches the end; slow is at the middle

Slow walks one node, fast walks two. When fast runs out, slow sits on the second middle for even length.

Fast covers twice the ground, so it finishes in n/2 slow steps — exactly the midpoint.

Algorithm

  1. Both pointers start at the head.
  2. While fast can take two steps, move slow once and fast twice.
  3. Return the suffix starting at slow.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def middleNode(self, head: list[int]) -> list[int]:        slow = fast = 0        n = len(head)        while fast + 1 < n:            slow += 1            fast += 2        return head[slow:]
Watch this run

03

Interactive walkthrough

Playing “Fast reaches the end; slow is at the middle”. Edit the input, hit Run, then scrub.

Approach: Fast reaches the end; slow is at the middle

Loading animation…