DSA AnimatorREVISION VIDEOS
← Back to problems
New

Middle of Linked List — LeetCode 876 video explanation

Given the head of a linked list, return the middle node. If there are two middle nodes, return the second one.

Loading videos…

DSA Animator › DSA Revision › Linked List › Middle of Linked List

Key moments in the Middle of Linked List video

0:04Problem0:10Example0:17Brute force0:24Key idea0:31Dry run0:41Code0:51Takeaway

What you will learn

Remember: when fast finishes, slow is halfway. This also finds the split point for palindrome and reorder problems. The video solves Middle of Linked List (LeetCode 876, Easy) with the Fast & Slow Pointers pattern from the Linked List topic, and you can replay every step in the interactive Middle of Linked List animation.

Middle of Linked List video transcript

Problem

Given the head of a linked list, return the middle node. If there are two middle nodes, return the second one.

Example

For 1, 2, 3, 4, 5, the middle is 3. For 1 to 6, there are two middles, 3 and 4, so return 4.

Brute force

Counting the length first and then walking half of it takes two passes. One pass is enough with two speeds.

Key idea

Move slow by one and fast by two. When fast reaches the end, slow has covered half the distance. So slow is at the middle.

Dry run

Both start at 1. Slow moves to 2, and fast to 3. Slow moves to 3, and fast to 5, the last node. Fast cannot move further, so the middle is 3.

Code

In code, loop while fast and fast dot next are not null. Move slow once and fast twice. Return slow, so it's O of n time and O of 1 space.

Takeaway

Remember: when fast finishes, slow is halfway. This also finds the split point for palindrome and reorder problems.

More Linked List revision videos

← All 185 DSA revision videos